Insert elements into a JavaScript array using the push() method
The array.push(element1, element2, ...) method in JavaScript is used to add one or more elements to the end of an array. The push() method overwrites the original array and change the array's length by the number of elements added to the array.
Where:
- array: specifies the array where the element will be inserting
- element1, element2, ..., elementX: one or more comma-separated elements to be inserted to the end of the array. At least one element must be specified
Insert elements into a JavaScript array using the unshift() method
The array.unshift(element1, element2, ...) method in JavaScript is used to add one or more elements to the front of an array. The unshift() method overwrites the original array and change the array's length by the number of elements added to the array.
Where:
- array: specifies the array where the element will be inserting
- element1, element2, ..., elementX: one or more comma-separated elements to be inserted at the array's beginning. At least one element must be specified
Insert elements into a JavaScript array using the splice() method
The array.splice(start, deleteCount, element1, ..., elementX) method in JavaScript is used to modify the contents of an array by deleting existing elements and/or adding new elements to the array. The splice() method modifies the original array.
Where:
- array: specifies the array where the element will be inserting
- start: an integer that specifies the array index from which elements will be removed from the array and added to the array. Negative values are allowed, in which case the index from which the method will be called will be calculated using the following formula: length + start
- deleteCount (optional): an integer specifying the number of elements to remove from the array, starting at the index specified in the start. If deleteCount is 0, then the elements are not deleted. If deleteCount is more significant than the number of remaining elements in the array, then all remaining elements of the array will be deleted
- element1, ..., elementX (optional): one or more elements to be inserted into the array. The array index at which new elements will be inserted corresponds to the start parameter.
Insert elements into a JavaScript array using spread operator
In JavaScript ES6 and above, we can use the spread operator ("..."). The spread operator is a flexible way of working with arrays popular in "new" JavaScript.