Array in JavaScript

JavaScript

In this post we are going to understand arrays in JavaScript with the help of examples, methods of an array, how to create an array and access elements, add elements/remove elements from an array.

What is array in JavaScript?


An array is an object type in Javascript that is used to store multiple elements of any data type(string, number, float, decimal) in a single variable. Each element of the array is correlated with a numeric index. The Index of the array’s first element is starting with 0. We often use an index to access the elements of an array.

1. How to create an array in JS


1. Array constructor

In this approach, we create an array object using a new keyword. It is not recommended approach.

//array constructor to create a new array
let myarray = new Array();

//array if we know the size of array
let myarray = new Array(10);

//create new array by passing elements
let myarray = new Array('A','B','C');

2. Array literal notation


The second way to create an array is by using an array literal notation. In practice, we use an array literal notation to create an array.

//array literal notation literal notation
let myarray = [];

2. Add single/multiple elements in Array


We can add elements to an array using an array. push() to add elements at end of the array and unshift() to add elements at end of the array.

Add single or multiple item at end of Array

Array.push() :Add single or multiple elements at end of array.

let students = [ 'Rack','Phys', 100];


//append a single new element end of an array

students.push('max');


console.log('add single item:',students)

let names = ['Tax','mack']

students.push(...names)

console.log('\n add mutiple elements  :',students)


Output

add single item: [ 'Rack', 'Phys', 100, 'max' ]

 add mutiple elements  : [ 'Rack', 'Phys', 100, 'max', 'Tax', 'mack' ]

Add single or multiple item at beginning of Array

unshift(): Add single or multiple elements at beginning of the array

let students = [ 'Rack','Tom'];


//add a single new element start of an array

students.unshift('max');


console.log(students)


let names = ['Tax','mack']
//add mutiple element at begging of array
students.unshift(...names)



console.log("append elements using spread operator:\n",students)

Output

[ 'max', 'Rack', 'Tom' ]
spread to add mutiple elements:
 [ 'Tax', 'mack', 'max', 'Rack', 'Tom' ]

Splice() to Add element at any Position

The splice() method changes the contents of the array by adding new elements or removing existing ones.

Syntax

array.splice(startIndex,no_of_element,element1,element2,....,elementn)

Parameters

  • startIndex: required parameter-specific start index to add or remove elements.
  • no_of_elements: optional parameter number of elements to remove or add.
  • element1,element2,….,elementN: optional parameter the new elements add to array.

Example add elements at postion in array

let students = [ 'Rack','Tom',
 'Max'];


students.splice(3,2,'Jack','Hans','dev')




console.log(students)

//output
[ 'Rack', 'Tom', 'Max', 'Jack', 'Hans', 'dev' ]

3. Get length of array


The length property is used to find the length of an array in javascript.

Example

let students = [ 'Rack','Tom',
 'Max','Kon','Unix','Avi'];

console.log(students.length)

//Output
6

4. Remove element from an array


We will understand how to remove elements at the end/start at any position in the array.

Remove element at end of array

Array.pop() : its remove last element from an array.

let students = [ 'Rack','Tom',
 'Max'];
students.pop()
console.log(students) 

//output
[ 'Rack', 'Tom' ]

Remove element at beginning of array

Array.shift() :its remove first element of an array.

Example

let students = [ 'Rack','Tom',
 'Max'];
students.shift()
console.log(students)
//output
[ 'Tom', 'Max' ]

Remove element at any postion

Array.splice() :-Array splice remove or insert elements at specific position.

Example

let students = [ 'Rack','Tom',
 'Max'];
students.splice(0,2)
console.log(students)

//output
['Max']

Some Useful method of array


5. Access elements of array


Each element of the array is correlated with a numeric index. The Index of the array’s first element is starting with 0. so we can use the index to access the elements of an array.

Syntax

var ele = arrayname[index]

Examples :Access single element of array

let students = [ 'Rack','Tom',
 'Max'];
console.log(students[0])

//output
Rack

6. slice an array in JavaScript


The array.slice() method returns a new array of selected elements based on the start and ends index from the original array. It does not change the original array else returns the new array.

Syntax

array.slice(startindex,endindex)

Parameters

  • startindex : The index at which the extraction or slicing of array start. .The defult value is 0.
  • EndIndex: An intege value specify where to end selection slicing or extraction.It default value is array.length.The negative endindex extract element from end.

Example

let students = [ 'Rack','Tom',
 'Max','Kon','Unix','Avi'];
subarray  = students.slice(0,3)
console.log(subarray)

//Output
[ 'Rack', 'Tom', 'Max' ]


//negative end index
subarray1  = students.slice(1,-2)
console.log(subarray1)

//Output
[ 'Tom', 'Max', 'Kon' ]

7. How to Check value is array


To check the value in the array we can use this instanceof operator and isArray() method.

instanceof: The instanceof operator return true when value is array type else returns false.

Example

let students = [ 'Rack','Tom',
 'Max','Kon','Unix','Avi'];
console.log(students instanceof Array)

//output
true

isArray() : It returns true when value is array type else returns false.

Example

let students = [ 'Rack','Tom',
 'Max','Kon','Unix','Avi'];
console.log(Array.isArray(students))


//output
true

Summary

In this post, we have understood the array in Javascript with examples.