Arrays in JavaScript | Types, Example

An array in JavaScript is an ordered set of data (or values) represented by a single variable name.

In JavaScript, an array is basically a user-defined object that represents a collection of different data type of elements.

Array uses a single variable name to store more than one value. These values are stored in indexed locations within an array.

We use an array when we want to store a group or list of related data in a single, easily managed location. For example, a list of names, books, favorite colors, courses, or prices is stored in an array.

Consider the below example where JavaScript array holds multiple favorite colors.

var colors = ['red', 'green', 'pink', 'yellow', 'black', 'white'];

Here, all six colors grouped together into an array and assigned to the colors variable. We can treat all the colors in a group, and we can access the individual colors when we need to.

How to create Arrays in JavaScript?

There are three ways to create an array in JavaScript. They are:

  • By array literal
  • By creating instance of Array directly (using new keyword)
  • Using an Array constructor (using new keyword)

JavaScript Array literal

Array literal is the most common and easiest way to create an array in JavaScript. The general syntax to create an array literal is as follows:

var arrayname = [value0, value1, value2, value3, ..... valueN];
const arrayname = [element0, element1, element2, ...... elementN];

In the above syntax, arrayname is a variable name assigned to array and values are contained inside [ ] and separated by , (comma). Look at the below figure in which we have created an array that holds four ice cream flavors as elements.

JavaScript array example

Value stored within an array can have several data types. The array named dataValues stores a numeric value, a text string, null value, and boolean value:

let dataValues = [10, "Hello", null, true];

The ability to store value of different types within an array is not of other programming language like Java. In Java language, all the values within an array must be of the same type.

We can also initialize an array with no data values within brackets. Consider the below example.

dataValues = [ ];

Elements and Indexes

When we create an array, each value is placed at a location or index in an array, as shown in the below figure.

JavaScript array example

Each value stored in an array is called element. Each element is identified by its location or index within an array. Indexes always begin with the number 0.

The first element in any array is at an index 0, the second element is at index 1, the third element is at index 2, and so forth. As shown in the above figure, the first element “vanilla” is at index 0, the second element “butterscotch” is at index 1, and so on.

We can also set a specific array value by its index using below syntax.

array[index] = value;

Here, index is the index number of the array element and value is the element stored at that position within an array. We could define the values of several elements in the flavors array using the following statements:

flavors[0] = "vanilla";
flavors[1] = "butterscotch";
flavors[2] = "lavender";
flavors[3] = "chocolate";

Arrays in JavaScript are dynamic. This means that they can automatically expand their size to store new elements. In the following code, we have declared flavors array with four elements.

Now we will set the value of an element with an index of four, the length of flavors array increases to five.

let flavors = ["vanilla", "butterscotch", "lavender", "chocolate"];
flavors[4] = "cookie dough"; // vanilla, butterscotch, lavender, chocolate, cookie dough stored in the array.

Example Program based on Array Literal

Let’s take a very simple program in which we will take five elements in an array and display on the web browser.

Program code 1:

   <title>JavaScript Arrays</title>
   let person = ["Deep", " Tripti", " Rashmi", " Amit", " Ivaan"];
   document.write(person); // Accessing full array.
      Deep, Tripti, Rashmi, Amit, Ivaan

Spaces and line breaks are not important in the array declaration. An array declaration can span more than one line.

Program code 2:

   <title>JavaScript Arrays</title>
   let cities = [
         " New York",
         " Sydney",
         " Mumbai",
         " Moscow"
    Dhanbad, New York, Sydney, Mumbai, Moscow

We can also create an array and then insert the elements like this:

Program code 3:

   let nums = [ ];
       nums[0] = 10;
       nums[1] = 20;
       nums[2] = 30;
       nums[3] = 40;
       nums[4] = 50;

For simplicity, readability and execution speed, you should always use the array literal method.

Creating Array directly using new keyword

Arrays in JavaScript are simple objects, so another way to create an array in JavaScript is by directly creating an instance of an object. The general syntax of creating array directly is as below:

let arrayname = new Array();

Here, we have used new keyword to create an instance of array. Let’s take an example of creating array directly.

Program code 4:

   <title>JavaScript Arrays</title>
// Creating an array using new keyword.
   let nums = new Array();
    nums[0] = 10;
    nums[1] = "John";
    nums[2] = 30;
    nums[3] = 50;
    nums[4] = true;

Creating Array using Object Constructor

Since arrays are objects, so we can declare and initialize an array using the new Array() object constructor. The general syntax for creating an array in JavaScript using object constructor is as follows:

let arrayname = new Array(elements);

Here, elements is comma-separated list of values stored in an array. We can declare and initialize months array as an array object using object constructor like this:

let months = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

We can also define arrays in JavaScript based on the number of elements within an array using new Object() constructor. The general syntax of creating an array with specified length is as:

let arrayname = new Array(arrayLength);

Here, arrayLength is the number of individual elements stored in the array. You must enter length argument as an integer between 0 and 2^32 – 1. The following code constructs monthName array with 12 elements:

let monthName = new Array(12);

Here, we have not initialized the array. JavaScript interpreter has allotted the memory for an array of length 12 to store 12 elements.

Accessing Array Elements in JavaScript

Each element in an array has its own index. To access elements of an array, just follow the array variable name with an index, surrounded by square brackets. The general syntax to access elements of an array is as:

let varname = arrayname[indexNumber];

For instance, the syntax to access the second element of the array and to assign to a variable is as:

let flavorOfDay = flavors[1];

In the above example, the 1 in brackets after flavorOfDay is the index number for the second element of the array. The index number is 1 because arrays start counting at 0 instead of 1.

Thus, you need to be careful when you want to access the correct element of an array with an index number. Look at the below figure to understand more clearly.

Accessing array element in JavaScriptLet’s write code to access all elements of the array flavors one by one.

Program code 5:

   <title>Accessing Arrays Elements in JavaScript</title>
   let flavors = ["vanilla", "butterscotch", "lavender", "chocolate"];
// Accessing array elements.
   let flavorOfDay1 = flavors[0]; // accessing the first array element.
   let flavorOfDay2 = flavors[1]; // accessing the second array element.
   let flavorOfDay3 = flavors[2]; // accessing the third array element.
   let flavorOfDay4 = flavors[3]; // accessing the last array element.

   document.write(flavorOfDay1, "<br>");
   document.write(flavorOfDay2, "<br>");
   document.write(flavorOfDay3, "<br>");

Updating Array Element

We can also use an array index to change or update an element in the array. The syntax is as:

// This sets the value of element at index 2 (previously "lavender") to a new value "chocobar".
   flavors[2] = "chocobar"; 

Let’s create a JavaScript program in which we will update the third element in an array.

Program code 6:

   <title>Updating Array Elements in JavaScript</title>
   let flavors = ["vanilla", " butterscotch", " lavender", " chocolate"];
   document.write("Before: " +flavors, "<br>");
// Updating third element.
   flavors[2] = " chocobar";
   document.write("After updating: " +flavors);
     Before: vanilla, butterscotch, lavender, chocolate
     After updating: vanilla, butterscotch, chocobar, chocolate

As you can see in the output that the third value of the element at index 2 has changed.

Array Length Property

Every JavaScript array has a property length that contains the number of array elements currently. The length property of an array returns the length of an array (array’s current size).

Length of an array is always one more than the last array index. The general syntax to get the length of an array is as:

let length = arrayname.length;

Consider the following example program.

Program code 7:

   <title>Array Length Property</title>
   let names = ["Tripti", "Deep", "Rashmi", "Ivaan", "John"];
// Getting the length of an array.
   let length = names.length;
   document.write("Length of array: " +length);
     Length of array: 5

As you can observe in the output that the value returned by the length property would be 5 but the highest index number is 4. This is because the length property of an array is always equal to one more than the highest index number in the array.

Null Element in JavaScript Arrays

In JavaScript, all elements of an array are initially null by default. An element having null value in an array actually does not exist. When a value is null, JavaScript interpreter does not store the elements in the computer’s memory.

As a result, they do not take up space in the memory, but they are considered elements in the array. Therefore, they are added to the array’s length property.

Consider the following example program where we will add a null element in an array and will determine the length of the array.

Program code 8:

   let names = ["Tripti", "Deep", null, "Rashmi", "Ivaan", ];
   document.write("Array elements: " +names, "<br>");
// Getting the length of an array.
   let length = names.length;
   document.write("Length of array: " +length);
     Array elements: Tripti,Deep,,Rashmi,Ivaan
     Length of array: 5

Program code 9:

// Creating an array of length 0.
   let num = new Array(); // array of zero element.
// Assigning null value to element 99.
   num[99] = null; // array of 100 elements.
   let length = num.length;
   document.write("Length of array: " +length);
     Length of array: 100

Note that the array does not take up any space in the computer’s memory, even after it is extended.

Types of Arrays in JavaScript

We must keep in mind that JavaScript is a loosely typed language. It means that elements of an array can be of different types. We can store different data types of elements in an array, even objects.

Basically, there are five types of arrays in JavaScript. They are:

  • String arrays
  • Number arrays
  • Boolean arrays
  • Object arrays (including null arrays because null is an object)
  • Mixed arrays

We will discuss each one type in the further tutorial.

Google Search JavaScript Arrays Questions

1. Does the order of elements in JavaScript array matter?

Ans: Most of the time, yes, the order of elements in array matter, but it depends. For instance, if we are creating an array just to store a list of randomly selected words, then we don’t need to care about the order of elements.

But, if we want storing words in alphabetical order, the order will matter. So, it is totally depends on you how you are using an array.

2. How many elements can we store into an array?

Ans: Theoretically, as many as we want. But practically, the number depends on the memory of computer. Each array element takes up a little space in the computer’s memory.

3. Can we have an empty array?

Ans: Yes, we can have an empty array. To construct an empty array, just write below code:

let emptyArray = [ ];

If you are creating an empty array, you can put elements to it later.

4. Can we put other elements in an array besides strings and numbers?

Ans: Yes, we can. In JavaScript arrays, we can put numbers, strings, booleans, other arrays, and even objects.

5. Is it necessary to put all the values of the same type in an array?

Ans: No, it is not essential that all the values in an array must have the same type.

6. Can I get the last element in JavaScript array?

Ans: We can use length property to get the last element of an array. To get the last element in the array, you can write the following code:

arrayname[arrayname.length - 1];

Let’s take an example in which we will get the last element of an array.

Program code 10:

   let fruits = ["Banana", "Apple", "Mango", "Guava", "Grapes", "Orange"];
   let getLastElement = fruits[fruits.length - 1];
   document.write("Last element of array: " +getLastElement);
      Last element of array: Orange

In this tutorial, you learned arrays in JavaScript with various example programs. Hope that you will have understood the basic concepts of JavaScript arrays.
Thanks for reading!!!
Next ⇒ JavaScript for in loop⇐ Prev Next ⇒

Please share your love