JavaScript Array.push() Method
-
Syntax of JavaScript
array.push()
: -
Example Code: Use
array.push()
to Add New Elements and Get the New Length of the Given Array -
Example Code: Use
array.push()
to Add the Elements of Another Array
In JavaScript, the array.push()
method can add new elements in an array. This method can also add another array’s elements after the given array’s last index.
Syntax of JavaScript array.push()
:
refarray.push(item1, item2);
refarray.push(arr2);
Parameters
item1 ,item2 ,itemN |
To add the new elements at the end of the array. |
arr |
To add all the elements after the refarray ’s last index. |
Return
This method will return the new length of the given array.
Example Code: Use array.push()
to Add New Elements and Get the New Length of the Given Array
In JavaScript, we can use the array.push()
method to add new elements at the end of a given array. The actual length of the array increase depending on the number of elements added.
In this example, we used the array.push()
method to get the new length of the array after adding two elements.
const array = ["javascript", "java"];
console.log(array.push("web","site"));
Output:
4
Example Code: Use array.push()
to Add the Elements of Another Array
Using the array.push()
method, we can add all the elements of an array after the last index of the given array.
We have created two arrays in this example, each with two elements. We will use the array.push()
method to add the elements of the second array and get the new length of the first array as output.
const array = ["file1", "file2"];
const arr = ["document1", "document2"];
console.log(array.push(arr));
Output:
3
The array.push()
method adds new elements and returns the new length of the given array.