JavaScript- Append in Array
These are the following ways to append an element to the JS array:
1. Using Array.push() Method
JavaScript array.push() Method is used to add one or more elements to the end of the array.
let a = [ 10, 20, 30, 40, 50 ];
a.push(90);
console.log(a);
Output
[ 10, 20, 30, 40, 50, 90 ]
2. Using Spread Operator with Array Literal
Javascript spread operator allows an iterable to expand in places where 0+ arguments are expected. It is mostly used in the variable array where there is more than 1 value is expected. It allows us the privilege to obtain a list of parameters from an array.
let a = [ 10, 20, 30, 40, 50 ];
// Pushing 90 to the original array
a = [ ...a, 90 ]
console.log(a);
Output
[ 10, 20, 30, 40, 50, 90 ]
3. Using JavaScript splice() Method
JavaScript splice() Method modifies the content of an array by removing existing elements and/or adding new elements. It allows us to add elements inside the array at specific index.
let a = [ 10, 20, 30, 40, 50 ];
// Update array using slice
a.splice(2, 0, 90);
console.log( a);
Output
[ 10, 20, 90, 30, 40, 50 ]
We can also append arrays in the existing array by combining them together.
4. Using JavaScript concat() Method
JavaScript concat() Method returns a new combined array comprised of the array on which it is called, joined with the array (or arrays) from its argument. This method is used to join two or more arrays and this method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.
let a1 = [ 10, 20 ]
let a2 = [ 30, 40 ]
let a3 = [ 50 ];
// Append a2 and a3 into a1
let a = a1.concat(a2, a3);
console.log(a);
Output
[ 10, 20, 30, 40, 50 ]