The push()
method in JavaScript is used to add one or more elements to the end of an array. It modifies the array by adding the new elements and returns the new length of the array.
Syntax
array.push(element1, element2, ..., elementN);
Parameters
Parameters | Description |
---|---|
element1, element2, …, elementN | The elements to add to the end of the array. |
Return Value
Return Type | Description |
---|---|
Number | The new length of the array after adding elements. |
Example 1: Using push() to Add Elements
This code demonstrates how to use the push()
method to add elements to the end of an array.
let Arr = [ 10, 20, 30, 40 ]; let newArr = Arr.push(50, 60); console.log(Arr); console.log(newArr);
Output:
[ 10, 20, 30, 40, 50, 60 ]
6
Example 2: Using push() with Spread Operator
You can also use the spread operator (...
) to add elements from another array.
let Arr = [ 10, 20, 30, 40 ]; let moreItems = [ 50, 60, 70 ]; Arr.push(...moreItems); console.log(Arr);
Output:
[ 10, 20, 30, 40, 50, 60, 70 ]
Example 3: Using push() to Add an Element
You can use push()
to add a single element to the end of an array.
let Arr = [ 1, 2, 3 ]; Arr.push(4); console.log(Arr);
Output:
[ 1, 2, 3, 4 ]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |