In this section, we will learn what the push() method is and how to use it in JavaScript.
JavaScript Arrays push() Method (JavaScript Append to Array)
The Array push() method is a way of adding new elements to an array.
These elements will be added to the end of the target array.
For example, if you have an array like [1,2,3] and used the push() method to add (4,5,6) to the array, these elements then will appear at the end of the array (after the value 3 for this example) and the final result becomes [1,2,3,4,5,6].
Note: this method changes the original array.
Array push() Syntax:
array.push(item1, item2, ..., itemX)
Array push() Method Parameters:
The arguments to the `push()` method are a variable number of elements that want to add to the array.
Array push() Method Return Value:
The return value of this method is the new length of the array that we’ve just added new elements to it.
Example: JavaScript adding to array via push() method
const arr = ["Tesla","Google"]; const length = arr.push("Microsoft","Amazon","Facebook","Twitter"); console.log(`The new length of the array is: ${length}`); console.log(arr);
Output:
The new length of the array is: 6 ["Tesla", "Google", "Microsoft", "Amazon", "Facebook", "Twitter"]