solvit.io

Append new elements at the end of a JavaScript array

Solution
// append just 1 element
theArray.push(element);

// append any number of elements
theArray.push(element1, element2, element3);

// append all the elements of another array
theArray = theArray.concat(anotherArray);

The push() method modifies the original array and returns an integer representing the new array length. The concat() method doesn't modify the original arrays and it returns an array with the result of concatenating the two arrays.

Example
var array = [1];

array.push(1);
// array = [1, 1]

array.push(2, 3, 5);
// array = [1, 1, 2, 3, 5]

var newArray = [8, 13, 21, 34];
array = array.concat(newArray);
// array = [1, 1, 2, 3, 5, 8, 13, 21, 34]
Find more solutions about: ,