JavaScript Array.push() Method

Shubham Vora Jan 30, 2023
  1. Syntax of JavaScript array.push():
  2. Example Code: Use array.push() to Add New Elements and Get the New Length of the Given Array
  3. Example Code: Use array.push() to Add the Elements of Another Array
JavaScript Array.push() Method

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.

Author: Shubham Vora
Shubham Vora avatar Shubham Vora avatar

Shubham is a software developer interested in learning and writing about various technologies. He loves to help people by sharing vast knowledge about modern technologies via different platforms such as the DelftStack.com website.

LinkedIn GitHub

Related Article - JavaScript Array