Array.push()
The Array.push()
method in JavaScript is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.
Syntax
</>
Copy
push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)
Parameters
Parameter | Description |
---|---|
element1, element2, ..., elementN | The elements to be added to the end of the array. These can be of any type, including objects, arrays, or primitives. |
Return Value
The push()
method returns the new length of the array after the elements have been added.
Examples
1. Adding a Single Element
This example demonstrates how to use push()
to add a single element to an array.
</>
Copy
const fruits = ["apple", "banana"];
const newLength = fruits.push("cherry");
console.log(fruits);
console.log(newLength);
Output
[ 'apple', 'banana', 'cherry' ]
3
- The array
fruits
now includes the new element"cherry"
. - The
push()
method returned the new length of the array:3
.
2. Adding Multiple Elements
You can use push()
to add multiple elements at once.
</>
Copy
const fruits = ["apple"];
const newLength = fruits.push("banana", "cherry");
console.log(fruits);
console.log(newLength);
Output
[ 'apple', 'banana', 'cherry' ]
3
- The elements
"banana"
and"cherry"
were added to the arrayfruits
. - The
push()
method returned the new length of the array:3
.
3. Using push()
with Objects
The push()
method can also be used to add objects to an array.
</>
Copy
const users = [{ name: "Akash" }];
const newLength = users.push({ name: "Bhairav" });
console.log(users);
console.log(newLength);
Output
[ { name: 'Akash' }, { name: 'Bhairav' } ]
2
- The object
{ name: "Bhairav" }
was added to theusers
array. - The
push()
method returned the new length of the array:2
.
4. Using push()
in a Function
You can use push()
in a function to dynamically add elements to an array.
</>
Copy
function addFruit(fruits, newFruit) {
fruits.push(newFruit);
return fruits;
}
const fruits = ["apple", "banana"];
console.log(addFruit(fruits, "cherry"));
Output
[ 'apple', 'banana', 'cherry' ]
The push()
method was used to dynamically add "cherry"
to the fruits
array.