Javascript Arrays


An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.



let fruits = ["Apple", "Banana"];
document.write(fruits.length);    //2

Live Demo!


An array is a single variable that is used to store multiple values in it. These multiple values are stored in indexed locations.

The individual elements are accessed by using the array name followed by the index value of the array element enclosed in [] square brackets.

The length of an array is same as the number of elements that it contains.


Example:


var cars = ["honda", "jaguar", "audi", "toyota"];

Live Demo!


In the above example, the array cars has a length of four & first index starting with 0. Hence, the last index value is n-1, i.e. 3, where n is the number of elements.

So, cars[1] index will have the value jaguar stored in it.



Declaring an array


Before using an array, it should always be declared, to make it easy for the compiler. It can be declared by following any one of the following techniques.



var house = [];            //method 1
var array_name = new Array();     //method 2



Example - Method 1:



// Initializing while declaring
var fruit = ["apple", "mango", "strawberry", "kiwi"];

Live Demo!


An array named fruit is created which contains four elements, apple, mango, strawberry and kiwi.

Example - Method 2:


// Initializing while declaring

// Creates an array having elements 2,3,5,7,11
var primeNum = new Array(2,3,5,7,11);

//Creates an array of 5 undefined elements
var abc = new Array(5);
abc[0] = 'one';
abc[1] = 'two';
abc[2] = 'three';
abc[3] = 'four';
abc[4] = 'five';

//Creates an array with element mango
var sweet = new Array("mango");

Live Demo!


As shown in above example, array primeNum contains 5 elements i.e. (2,3,5,7,11) while array abc contains 5 undefined elements instead of having a single element 5.

Therefore, this method is generally not preferred when working with numbers but, it works fine with Strings and Boolean.
As shown in the example above, array sweet contains a single element mango.

However, method 2 i.e. using built-in array constructor new array(), only complicates the code and might produce some unexpected results.
Hence, method 1 is preferred over method 2.

Furthermore, JavaScript automatically extends the length of an array when new array elements are initialized.


For example:


cust_orders = new Array();
cust_orders[5] = "lion pencils";
cust_orders[10] = "steadler eraser";

Live Demo!

When JavaScript encounters the reference to cust_orders[5] as mentioned in the above example, it will extend the size of the array cust_orders to 6 and initialize cust_orders[5].

And when JavaScript encounters a reference to cust_orders[10] in the above example, it will extend the size of a array cust_order to 11 and initialize order[10].


Manipulating an Array Element


By using the index number, we can access and manipulate data already stored in that index value.


For example:


var fruit=["apple","mango","strawberry","kiwi"];
fruit[0]= "guava";
document.getElementById("demo").innerHTML=fruit[0];

Live Demo!

The first element apple will be replaced by guava.


Accessing the First Array Element.


Example:


<!DOCTYPE html>
<html>
<head>
  <title>Learning Javascript</title>
</head>
<body>

<h2>JavaScript Arrays</h2>
<p>Accessing the first array element in JS.</p>
<p id="demo"></p>

<script>
  fruit=["apple","mango","strawberry","kiwi"];
  var first = fruit[0];
  document.getElementById("demo").innerHTML = first;
</script>

</body>
</html>

Live Demo!


The value of first element of the array fruit will be saved in variable first which will then be used to display it.


Accessing the Last Array Element.


Example:


<!DOCTYPE html>
<html>
<head>
  <title>Learning Javascript</title>
</head>
<body>

<h2>JavaScript Arrays</h2>
<p>Accessing the last array element in JS.</p>
<p id="demo"></p>

<script>
  var fruit=["apple","mango","strawberry","kiwi"];
  var last = fruit[fruits.length-1];
  document.getElementById("demo").innerHTML = last;
</script>

</body>
</html>

Live Demo!


length-1 property is used to calculate the last index value of the array fruit which is then assigned to variable last.


The Elements of an Array


In JavaScript there is no restriction on the values that can be assigned to the elements of an array. These values could be of different types or could refer to other areas or objects.

We use it when we want to store a list of elements and access them by a single variable.

Arrays are special kinds of objects. This allows us to have variables of different types in the same Array.


We can have objects in an array and functions in the same array as well. We can even have arrays in an Array:


multiTypeArray[0] = 12;
multiTypeArray[1] = myFunc;
multiTypeArray[2] ="string";
multiTypeArray[3] = new array(3,4);

Live Demo!


The last element of the array, multiTypeArray, contains a dense area as its value.
The two elements of this area can be accessed using a second set of subscripts:

num1=multiTypeArray[3][0];

num2=multiTypeArray[3][1];


JavaScript Array Const (ES6)


The const keyword was introduced in 2015 (ECMAScript 2015) in JavaScript ES6. Arrays are now commonly declared using the const keyword.


An array cannot be reassigned if it is declared using the const keyword.



const foods = ["Pizza", "Burger", "Chicken", "Steak"];
foods = ["Fries", "Pie", "Cookies"]; //ERROR



The const keyword is not used to define a constant array, it only defines a constant reference to the array.


For an array declared with const keyword, the elements can be reassigned.



const foods = ["Pizza", "Burger", "Chicken", "Steak"];
foods[1] = "Fries"; //Changes Burger to Fries
foods.push("Cookies"); //Adds Cookies to the foods array

Live Demo!


Arrays declared by the const keyword have a Block scope i.e. An array that is declared in a block is not the same as the array declared outside the block. However, arrays declared with var do not have block scope.