JavaScript Array.push() Method

Usage — The JavaScript Array.push() method is used to add one or more elements to the end of an array.

It has the following syntax:

arr.push([element1[, ...[, elementN]]])

Here is an example of using Array.push():

var numbers = [1, 2, 3];
numbers.push(4);

// Output — [1, 2, 3, 4]
console.log(numbers);

numbers.push(5, 6, 7);

// Output — [1, 2, 3, 4, 5, 6, 7]
console.log(numbers);

Return Value — This method returns the new length property of the object upon which the method was called.

Additional Information — This Array.push() method is intentionally generic. It can be used with call() or apply() on objects resembling arrays.

The push method relies on a length property to determine where to start inserting the given values. If the length property cannot be converted into a number, the index used is 0. This includes the possibility of length being nonexistent, in which case length will also be created.

The only native, array-like objects are strings, although they are not suitable in applications of this method, as strings are immutable.

Browser Support — The Array.push() method is available in Chrome, Edge, Firefox, Internet Explorer 5.5+, Opera and Safari.

Go Directly To — usage, parameters or working examples.

Parameters

elementN

The elementN parameter is used to specify the elements to add to the end of the array. The first parameter is required and the rest of them are optional.

Working Examples

Here are some examples of using the Array.push() method:

var sports = ['soccer', 'baseball'];
var total = sports.push('football', 'swimming');

// Output — ['soccer', 'baseball', 'football', 'swimming']
console.log(sports);

// Output — 4
console.log(total);
var vegetables = ['parsnip', 'potato'];
var moreVegs = ['celery', 'beetroot'];

Array.prototype.push.apply(vegetables, moreVegs);

// Output — ['parsnip', 'potato', 'celery', 'beetroot']
console.log(vegetables);

In the following example, the length property of the object is increased by 1 every time we push an element into it.

var obj = {
    length: 0,

    addElem: method addElem(elem) {
        [].push.call(this, elem);
    }
};

obj.addElem({});
obj.addElem({});

// Output — 2
console.log(obj.length);

Further Reading

  1. You can read more about the JavaScript Array.push() method on MDN.
  2. You can also take a look at the defeinition of JavaScript Array.push() method in the ECMAScript 2015 specification.

Reader Comments

1. You can register or login to post a comment. Asking readers to register improves the quality of discussion.

2. As a registered user, you will also get to access features like choosing between a light and dark theme or anything else that we might implement in future.

Follow Us For Updates

FacebookTwitterGoogle+
Go To Top