JavaScript Array push() Method
The push() method in JavaScript adds one or more elements to the end of an array and returns the new length of the array. It modifies the original array, increasing its length by the number of elements added.
Syntax
arr.push(element0, element1, … , elementN);
Parameters
This method contains as many numbers of parameters as the number of elements to be inserted into the array.
Return value
A Number – New length of the array.
Example: In this example, function func() initializes an array with elements ‘GFG’, ‘gfg’, ‘g4g’, then pushes the string GeeksforGeeks to the end of the array using the push() method. Finally, it logs the updated array to the console.
function func() {
let arr = ['GFG', 'gfg', 'g4g'];
// Pushing the element into the array
arr.push('GeeksforGeeks');
console.log(arr);
}
func();
Output
[ 'GFG', 'gfg', 'g4g', 'GeeksforGeeks' ]
Example: In this example we use The function func() initializes an array `arr`, adds elements [23, 45, 56]` to it using push(), then logs the modified array to the console.
function func() {
// Original array
let arr = [34, 234, 567, 4];
// Pushing the elements
arr.push(23, 45, 56);
console.log(arr);
}
func();
Output
[ 34, 234, 567, 4, 23, 45, 56 ]
JavaScript Array push() Method UseCase
1. What is the use of the push() method in JavaScript Arrays
The `push()` method in JavaScript arrays is used to add one or more elements to the end of an array. It modifies the original array by appending the new elements and returns the updated length of the array.
2. How to push an array into the object in JavaScript ?
The array push() function adds one or more values to the end of the array and returns the new length. This method changes the length of the array. An array can be inserted into the object with push() function.
We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.