Skip to main content

What does push() do?

The push() method is one of the most frequently used in JavaScript. It adds one or more elements to the end of an array and returns the new length of the array.


Example:

javascript
const fruits = ["apple", "banana"]; const newLength = fruits.push("cherry"); console.log(fruits); // ["apple", "banana", "cherry"] console.log(newLength); // 3
  • The method modifies the original array (mutates it).
  • It returns not the array itself, but the number of elements after adding.

You can add several elements at once:

javascript
const arr = [1, 2]; arr.push(3, 4, 5); console.log(arr); // [1, 2, 3, 4, 5]

Behavior:

  • Elements are added to the end of the array.
  • The indexes of the new elements start at the current length.
  • The return value is the new value of arr.length.

Important:

  • push() only works with arrays (or array-like objects).

  • If you do arr = arr.push(...), you lose the array itself:

    javascript
    const arr = [1, 2]; arr = arr.push(3); // mistake - arr becomes a number (3)

In short:

What it doesAdds elements to the end of the array
Modifies the original array?Yes
ReturnsThe new length of the array
Can add several elementsYes
Examplearr.push(1, 2, 3)

Alternative (without mutation):

If you want to add an element without changing the original:

javascript
const arr = [1, 2]; const newArr = [...arr, 3]; console.log(newArr); // [1, 2, 3] console.log(arr); // [1, 2] (unchanged)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.