Method
Introduction to the JavaScript Array push() Method
The JavaScript Array push() method adds one or more elements to the end of an array and returns the new length of the array. It is one of the most commonly used methods for manipulating arrays in JavaScript.
Syntax of the Array push() Method
The syntax of the push() method is as follows:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
array.push(element1, ..., elementN)
[/dm_code_snippet]
Here, the array is an existing Array object. The element1, … , elementN are the elements that are to be added to the end of the array.
Examples of Using the JavaScript Array push() Method
Let’s look at some examples to understand how the push() method works.
Example 1: Adding a Single Element to an Array
In this example, we will add a single element ‘blue’ to the end of an array.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
let colors = ['red', 'green']; let newLength = colors.push('blue'); console.log(colors); // ['red', 'green', 'blue'] console.log(newLength); // 3
[/dm_code_snippet]
In the example above, we first define an array called ‘colors’ which contains two elements ‘red’ and ‘green’. Then, we use the push() method to add a new element ‘blue’ to the end of the array. Finally, we print out the resulting array and the new length of the array.
Example 2: Adding Multiple Elements to an Array
In this example, we will add multiple elements ‘yellow’, ‘orange’ and ‘purple’ to the end of an array.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
let fruits = ['apple', 'banana']; let newLength = fruits.push('yellow', 'orange', 'purple'); console.log(fruits); // ['apple', 'banana', 'yellow', 'orange', 'purple'] console.log(newLength); // 5
[/dm_code_snippet]
In the example above, we define an array called ‘fruits’ which contains two elements ‘apple’ and ‘banana’. Then, we use the push() method to add three new elements ‘yellow’, ‘orange’ and ‘purple’ to the end of the array. Finally, we print out the resulting array and the new length of the array.
Conclusion
In this tutorial, we learned about the JavaScript Array push() method. We saw how to use the push() method to add one or more elements to the end of an array and how to get the new length of the array.
We hope you found this tutorial helpful and you now have a better understanding of the JavaScript Array push() method.