What is an Array?
An array is a collection or a list of similar items logically grouped together.
Similar items means values which represent a particular type of entity.

Examples are names of car companies, list of car models, laptop types, smartphone brands etc.

Similar items in above definition does NOT mean those which have the same data type such as a list of strings, list of numbers or a list of boolean values.
A single array in javascript can contain a string, an integer, a decimal value, an object and an array also. Thus, array in javascript is just a logical group of values.

Array Syntax
A javascript array is surrounded by square brackets (‘[‘ & ‘]’).
Elements of the array are separated by a comma(,). An array is assigned to a variable which becomes the name of the array.

Name of variable is user defined. It is not mandatory to assign an array to a variable but you have to do it if you want to use it anywhere else.
Thus, an array looks like

var cars = ['Honda', 'Hyndai', 'BMW', 'Audi'];

var laptops = ['Dell', 'Sony', 'Lenovo'];

//different data types
var hybrid = [1.2, 'string', true, 24];

//array inside array
var ramSizes = [8, 16, 32, 64];
var laptops = ['Dell', 'Sony', 'Lenovo', ramSizes];

How to create an Array

There are 2 ways to create an array

  • Using array literal
    Create 2 enclosing square brackets, place the array values inside them and assign it to a variable. Just as shown in examples above. Simple as that.

    var arrayName = [element1element2, …..];

  • Using new keyword
    Using this approach, an array can be created using the below syntax

    var arrayName = new Array(element1, element2, ….);

    We are creating an array object using its constructor. Syntax is similar to previous approach but is not the preferred way.
    Elements can be of any type as in earlier approach.

    If you provide a single numeric argument to the constructor, then it is considered as the size of the array.
    That is, var arrayName = new Array(5) will create an array of 5 elements and not an array with a single element whose value is 5.
    Thus, in order to create array with this approach and add elements to it, 2 statements are required.

Adding elements to Array
Javascript arrays have a push method which allows you to add elements to an array.
It takes the element to add as argument and adds the element to the end of array.

push returns the length of the array. Also, more than 1 elements may be added to the array using push method. Example,

var evenNumbers = [0, 2, 4, 6];
evenNumbers.push(8);      // array becomes [0, 2, 4, 6, 8]
var length = evenNumbers.push(10, 12, 14);    // length will be 8

push returns the length of the array after the element is added.
Accessing Array Elements
Array elements are index based(index starts at 0) and its elements can be accessed using indexes. Syntax to access an array element is :

var element = arrayName[ elementIndex];

Thus, to access first element of an array, following syntax is used

var laptops = ['Dell', 'Sony', 'Lenovo'];
var l = laptops[1];     // This returns Sony

Iterating over Array
A javascript array can be iterated using a for loop.
Since array indexes start at 0, the loop starts from 0. Also, array has a length property which returns the total number of elements in the array.
Thus, the last element of the array will have index = length – 1.
Therefore, to iterate over an array, a for loop starting from 0 to length – 1 can be used.
Example,

var laptops = ['Dell', 'Sony', 'Lenovo'];
for (var index = 0; index < laptops.length; i++) {
   console.log('Laptop : '+laptops[index]);
}

In order to iterate over an array for...of loop can also be used. It is a newer feature in javascript.
Syntax is:

var laptops = ['Dell', 'Sony', 'Lenovo'];
for (let lappy of laptops) {
   console.log('Laptop : '+lappy);
}

let followed by a name declares a variable. In each iteration, this variable contains the current array element.

Common Array Methods
Following are the commonly used javascript array methods

Method Description Usage
push Used to add an element to array.(Has been discussed above)
toString Converts an array to a string of comma separated values
var laptops = ['Dell', 'Sony', 'Lenovo'];
laptops.toString();
// returns Dell, Sony, Lenovo

 

pop Returns the last element of the array. The element is also removed from the array.
var laptops = ['Dell', 'Sony', 'Lenovo'];
laptops.pop(); //returns Lenovo
// array is now ['Dell', 'Sony']

 

shift Returns the first element of the array. The element is removed from the array and all the remaining elements are shifted towards the left.
var laptops = ['Dell', 'Sony', 'Lenovo'];
laptops.shift(); //returns Dell
// array is now ['Sony', 'Lenovo']

 

join Returns a string combined with a separator. The separator is passed as an argument to this method.  

var laptops = ['Dell', 'Sony', 'Lenovo'];
laptops.join(' & ');
//returns Dell & Sony & Lenovo

 

 

unshift This method is opposite of shift method.
It adds an element to the beginning of the array and shifts other elements to the right.
The element to be added is passed as an argument to this method.
This method returns the new length of the array.
var laptops = ['Dell', 'Sony', 'Lenovo'];
laptops.unshift('Apple'); //returns 4
// array is now ['Apple', 'Dell', 'Sony', 'Lenovo']

 

slice Accepts two integers as arguments and returns the array of elements whose indexes lie in between the two arguments.
Note that the indexes are zero-based and array elements till (second argument – 1) are considered.
var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
laptops = laptops.slice(1,2);
// returns ['Dell']

 

sort This method sorts an array in alphabetical order.
If the array is of numbers, then it sorts the array from low to high values.
var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
laptops.sort();
// returns ['Apple', 'Dell', 'Lenovo', 'Sony'];

 

reverse Reverses the elements of the array.
That is, last element becomes the first, second last becomes the second element and so on.
var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
laptops.sort();
// returns ['Lenovo', 'Sony', 'Dell', 'Apple']

 

indexOf This method accepts an array element as argument and returns the index of that element inside the array.
It returns -1 if the element does not exist in the array.
This method can be used to check if an array contains an element.
var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
laptops.indexOf('Dell');
// returns 1

 

How to recognize Array
Suppose you want to test whether a given variable represents an array or not.
One will suggest to use typeof operator.
But the problem is that typeof used on array will return “object“. This is because an array is also an object.

So, the question is how to tell whether a variable represents an array. Following methods will be useful in this case.

Method 1 : Using instanceof operator
instanceof operator used on array variable will return true if the variable is an array, false otherwise. Example,

var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
laptops instanceof Array     //will return true

Method 2 : Using isArray method

Array object defines a method isArray which takes an argument which will return true if the argument is an array, false otherwise. Example,

var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
Array.isArray(laptops);           // returns true
var value = 5;
Array.isArray(value);             // returns false
Array.isArray(new Array());       // returns true
Array.isArray();                  // returns false

This method was introduced in ECMAScript 5 and will not work in older browsers.

Method 3 : Using constructor property

Array variable has a constructor property. This property returns the function name which created the array.
Converting the value to a string using toString method returns a string representation of this function.
Now, whether the variable is an array can be tested by checking the presence of “Array” in this string.
Example,

var laptops = ['Apple', 'Dell', 'Sony', 'Lenovo'];
var functionName = laptops.constructor;            // returns Array()
var functionStr = functionName.toString();         // returns function Array() { [native code] }
var isarray = functionStr.indexOf("Array") > -1;   // returns true

Leave a Reply