JavaScript Array push() Method

JavaScript array push() function is “used to add a new element at the end of an array and returns the new length”.

Syntax

array.push(element)

You can use a push() method to append more than one value to an array in a single call.

array.push(item1, item2, item3,...,itemN)

Parameters

item1, item2: It takes item1, item2 to add to the Array.

Return Value

It returns the number representing the new length of the Array.

Example 1: How to Use array.push() function

The array push() method accepts an element and appends it to the array.

The push() method modifies the length of the Array or collection and can append a number, string, object, array, or any value to the array.

data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)

Output

The modified array is: [ 'Python', 'Javascript', 'PHP', 'Golang' ]
The length of modified array is: 4

Example 2: How to add elements to an array

Adding elements in the JavaScript array means appending as many elements as possible, like integers, strings, arrays, objects, an array of strings, an array of integers, and an array of arrays.

Let us take the example of Node.js to understand how to add an item in an array in JavaScript.

const songs = ['Dangerous', 'Thriller'];
const totalSongs = songs.push('Stranger In Moscow');

console.log(totalSongs);

console.log(songs);

Output

3
[ 'Dangerous', 'Thriller', 'Stranger In Moscow' ]

Example 3: How to add multiple elements in the Array

To add multiple elements in the JavaScript array, use the array.push() function. We can add multiple elements as arguments at a single time.

data = ['Python', 'Javascript', 'PHP']
len = data.push('Golang', 'C#', 'Swift')
console.log('The modified array is: ', data)
console.log('The length of modified array is: ', len)

Output

The modified array is: [ 'Python', 'Javascript', 'PHP', 'Golang', 'C#', 'Swift' ]
The length of modified array is: 6

Example 4: Appending elements of an array to another array

You can use the for…of loop to iterate over the elements of the array and use the push() method to append each element to another array.

let cars = ["maruti", "tata", "kia"];
let luxury = ["bmw", "audi", "land rover", "mercedez"];

for (const lux of luxury) {
  cars.push(lux);
}

console.log(cars);

Output

[ 'maruti', 'tata', 'kia', 'bmw', 'audi', 'land rover', 'mercedez' ]

That’s it.

1 thought on “JavaScript Array push() Method”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.