JavaScript push() method allows us to add elements in an array. This write-up is mainly focused on the following outcomes:
- What is the array push() method in JavaScript
- How to add elements in the array using the push() method
- How to add elements in an empty array using the push() method
What is the array push() method in JavaScript
In JavaScript, the array push() method is used to add one or more elements at the end of the array. This method changes the array size and a new array is returned as an output. The elements it takes as a parameter are directly added to the array. We can use this method to append numerous elements to an array.
Syntax:
With the help of the above syntax, we can add elements in an array. Now let’s understand the push() method using the above syntax.
Code:
add=cars.push("Roll Royce","Ford Mustang")
console.log(add)
In this code we create an array of cars and add two more elements Roll Royce and Ford Mustang to it using the push() method.
Output:
The above output shows that the push() method adds Roll Royce and Ford mustang at the end of the array which eventually changes the original array size and returns a new array as an output.
How to add elements in an array using the push() method?
We can also add elements in an array at once so we don’t have to write them one by one as parameters while using the push() method.
Code:
for (var a=1; a<=5; a++)
cars.push(a)
console.log(cars)
In this code we create an array of cars having 4 elements in it. Then we use a push() method inside a for loop in order to add numbers into the array.
Output:
This output shows that elements are added at the end of the array using a for loop which changes the original array size and returns a new array as output.
How to add elements in an empty array using the push() method?
We can also add elements to an empty array at once so we don’t have to write them one by one as parameters while using the push() method.
Code:
for (var a=1; a<=10; a++)
cars.push(a)
console.log(nums)
In this code we create an array having no element in it. Then we use a push() method inside a for loop in order to add numbers into the array.
Output:
This output shows that the array was empty and then we use a for loop to add elements.
Here you go! You can now append or fill elements to a non-empty or empty array respectively.
Conclusion
JavaScript array push() method adds elements in an array at the end position. The push() method takes the elements as a parameter and then adds them at the end. In this article, we have briefly described the working and usage of the array push() method in JavaScript. We hope you will like our information regarding the JavaScript array push() method.