JavaScriptArrays

Array.prototype.push()

Adds elements to the end of an array and returns its new length.

Returns
The new length of the array.
Changes the original
Yes
On this page

Example

#
JavaScript
const cart = ['HTML Course']
const newLength = cart.push('CSS Course', 'JS Course')

console.log(newLength)
console.log(cart)
Console
3
['HTML Course', 'CSS Course', 'JS Course']

Definition and usage

#

The push() method appends one or more elements to the end of the array. It changes the original array and returns its new length, not the array itself.

It’s the most common way to add data: a new chat message, a task on a list, a result in the history.

In code built around data immutability (like React state), you create a new array instead of using push(): [...items, newItem].

Syntax

#
Syntax
array.push(element1, element2, …)

Parameters

#
  • element1…elementN

    any values

    The elements to add at the end.

More examples

#
A non-mutating version
JavaScript
const cart = ['HTML Course']
const updated = [...cart, 'Python Course']

console.log(cart)
console.log(updated)
Console
['HTML Course']
['HTML Course', 'Python Course']

Browser support

#

Widely available

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • Don’t assign the result of push() back to the array: list = list.push(x) turns the array into a number.
  • To merge two arrays, use concat() or the ... syntax, not push() with an array (it would add the whole thing as a single element).

Related entries

#

Spotted a mistake or missing an example? Write to us.