February 2018
Intermediate to advanced
298 pages
8h 22m
English
Sometimes, we may need to push the values of an existing array into the end of another existing array. This is how programmers used to do it:
var array1 = [2,3,4];var array2 = [1];Array.prototype.push.apply(array2, array1);console.log(array2); //Output "1, 2, 3, 4"
But from ES6 onward we have a much cleaner way to do it, which is as follows:
let array1 = [2,3,4];let array2 = [1];array2.push(...array1);console.log(array2); //Output "1, 2, 3, 4"
Here the push method takes a series of variables and adds them to the end of the array on which it is called. See the following line:
array2.push(...array1);
This will be replaced with the following line:
array2.push(2, 3, 4);
Read now
Unlock full access