How to Use the Array push() Method in JavaScript

  • 2 min read
  • November 30, 2020
linkedin twitter facebook reddit
linkedin twitter facebook reddit

The Array push() method adds elements to the end of an array.

Basic Array.push() example

The following example shows how to use the Array.push() method to add an element to an array:

const fruits = ['peach', 'mango', 'banana'];
fruits.push('strawberry');
console.log(fruits);
// Expected output:
// ["peach", "mango", "banana", "strawberry"]

In the above example, the fruits array initially contains 3 items (defined in the first line of code). The push() method is used to add a fourth item – strawberry – to the fruits array. This item is added at the end of the array as its last item.

Syntax

The syntax of the push() method is as follows:

arrName.push(element1, element2elementN)

This method accepts multiple items to add, as the example below demonstrates:

fruits.push('apple', 'pear');
console.log(fruits);
// Expected output:
// ["peach", "mango", "banana", "strawberry", "apple", "pear"]

In the above example, two additional items are added to the end of the fruits array: apple and pear. Both items are pushed onto the end of the provided array in the order in which they appear – first “apple”, then “pear”. The two new elements appear at the end of the fruits array.

Return value

The push() method returns the length of the new array after the items have been added:

const nums = [1, 2, 3, 4, 5];
const newLength = nums.push(6);
console.log(nums);
// Expected output: [1, 2, 3, 4, 5, 6]
console.log(newLength);
// Expected output: 6

In the example above, the number 6 is added to the nums array by applying the push() method. The return value of push() is stored in const newLength. As the above code shows, the new length of the array (i.e. the number of items it contains) is 6 after the addition of the final element.

 

Related Articles

JavaScript – How to Use the includes() Method

JavaScript – A Short Introduction to Loops

JavaScript – How to Search Arrays

Related Posts

How to Change CSS Using JavaScript

How to Change CSS Using JavaScript

Cascading Style Sheets (CSS) is used to design the layout of a webpage. CSS is a set of structured rules describing the layout of elements in

How to Use the for…in Statement in JavaScript

How to Use the for…in Statement in JavaScript

The for…in statement is used to loop through an object’s properties. Basic for…in loop example The following code demonstrates a basic example using the for…in statement

How to use the for…of Statement in JavaScript

How to use the for…of Statement in JavaScript

The for…of statement was introduced in ECMAScript2015 (ES6) and adds a powerful new type of loop to JavaScript. JavaScript offers many different types of loops, each