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 Use Cookies with JavaScript

How to Use Cookies with JavaScript

Cookies make it possible to store information about a web application’s user between requests. After a web server sends a web page to a browser, the

How to Get an Object’s Keys and Values in JavaScript

How to Get an Object’s Keys and Values in JavaScript

In JavaScript, getting the keys and values that comprise an object is very easy. You can retrieve each object’s keys, values, or both combined into an

How to Use the toLowerCase() method in JavaScript

How to Use the toLowerCase() method in JavaScript

JavaScript’s toLowerCase() method takes a string and converts it into a new string consisting of only lowercase letters. Remember: JavaScript strings are immutable. This method will