JavaScript Array

An array is a type of object that may hold several values at the same time.

const arr = ['welcome', 'to', 'androidaura'];

// var arr = [element0, element1, ..., elementN];

Here, arr is an array. There are three values stored in it.

Two ways to create an array

  • Using an array literal
  • Using the new keyword

Using an array literal

const arr = ["hello", "world"];

Using the new keyword

const arr = new Array("hello", "world");

Lets take an example of creating array

var person=new Array("Vishal","Akshay","Midhun");  

    for (i=0;i<person.length;i++){  

// output
// Vishal
// Akshay
// Midhun

The following example demonstrates how to retrieve specific array elements by index.

var person = ["Nirav", "Anu", "Jancy", "Shweta"];

console.log(person[0]);  //Nirav
console.log(person[1]);  //Anu
console.log(person[2]); //Jancy
console.log(person[person.length - 1]); //Shweta

How to get length of an array

var person=new Array("Ruchika","Vishal","Seema");  

//output 3

Adding new element

var person=new Array("Vishal","Akshay","Midhun");  
person.push("aarush")        // [ 'Vishal', 'Akshay', 'Midhun' ]

console.log(person.length);  // 4
console.log(person);        // [ 'Vishal', 'Akshay', 'Midhun', 'aarush' ]

Adding new element to beginning of an array

var person=new Array("Vishal","Akshay","Midhun");  
person.unshift("aarush")      // [ 'Vishal', 'Akshay', 'Midhun' ]

console.log(person.length);   // 4
console.log(person);          // [ 'aarush', 'Vishal', 'Akshay', 'Midhun' ]

Removing last element from an Array

var person=new Array("Vishal","Akshay","Midhun"); 

console.log(person);  // [ 'Vishal', 'Akshay' ]

Removing first element from an Array

var person=new Array("Vishal","Akshay","Midhun"); 

console.log(person);  // [ 'Akshay', 'Midhun' ]

Merging Arrays

var person1=new Array("Vishal","Midhun"); 
var person2=new Array("Shweta","Anupriya"); 
var person = person1.concat(person2);

console.log(person);  // [ 'Vishal', 'Midhun', 'Shweta', 'Anupriya' ]