Adding Elements to an Array with Javascript

Adding Elements to End of the Array

The push() method can be used to add one or more elements to the end of an array.

var arr = [1, 2, 3, 4];

// add single element
arr.push(5);

// [1, 2, 3, 4, 5]
console.log(arr);

// add multiple elements
arr.push(6, 7, 8);

// [1, 2, 3, 4, 5, 6, 7, 8]
console.log(arr);

Return value : New length of the array.

var arr = ['A', 'B', 'C', 'D'];

var size = arr.push('E', 'F');

// 6
console.log(size);

Adding Elements to Front of the Array

The unshift() method can be used to add one or more elements to the front of an array.

var arr = [1, 2, 3, 4];

// add single element
arr.unshift(5);

// [5, 1, 2, 3, 4]
console.log(arr);

// add multiple elements
arr.unshift(6, 7, 8);

// [6, 7, 8, 5, 1, 2, 3, 4]
console.log(arr);

Return value : New length of the array.

Adding Elements At Any Position in the Array

The splice() method can be used to modify an array by adding or removing elements starting from any index.

  • The first parameter specifies the start position from where to modify the array :
    • 0 means the start of the array
    • Negative values signify the starting position from the end of the array. -1 would mean the last element as the start position. -2 would mean the second-last element as the start position.
    • Values greater than the length of the array signifies the starting position = length of the array.
  • The second parameter specifies how many elements need to be deleted. We don't need to delete elements in this case, so we pass the value 0 here.
  • Starting from the third parameter we can specify the elements that are to be added. Each element that is to be added is passed as a parameter.

Example 1 - Adding 2 elements starting from second position :

var arr = [1, 2, 3, 4];

// add 5 & 6 at position = 1
arr.splice(1, 0, 5, 6);

// [ 1, 5, 6, 2, 3, 4 ]
console.log(arr);

Example 2 - Adding an element to start of the array :

var arr = [1, 2, 3, 4];

// add 5 at position 0
arr.splice(0, 0, 5);

// [ 5, 1, 2, 3, 4 ]
console.log(arr);

Example 3 - Adding 3 elements to end of the array :

var arr = [1, 2, 3, 4];

// first parameter is greater than the length of the array
// so start position = length of the array = 4
arr.splice(10, 0, 5, 6, 7);

// [ 1, 2, 3, 4, 5, 6, 7 ]
console.log(arr);
Reversing an Array with Javascript
Removing Elements from an Array with Javascript