There are three ways to add elements to a JavaScript array.
There are three ways to add elements to a JavaScript array.
- With the push() method, you can add one or more elements to the end of an array and it will return the new length of the array. For example:
var arr = [1, 2, 3];
arr.push(4); // [1, 2, 3, 4]
- By using the unshift() method, you can add one or more elements to the beginning of an array and it will return the new length of the array. For example:
var arr = [2, 3, 4];
arr.unshift(1); // [1, 2, 3, 4]
- The concat() method is used to merge two or more arrays and return a new array. You can use the concat() method to merge the elements to be added into a new array, and then replace the original array with the new array. For example:
var arr = [1, 2];
var newArr = arr.concat(3); // [1, 2, 3]