The .push() method is one of the most commonly used array methods in JavaScript. It is used to add one or more elements to the end of an array.

A key thing to remember is that .push() mutates (changes) the original array and returns the new length of the array.

1. Basic Syntax

You simply call the method on the array and pass the items you want to add as arguments.

JavaScript
const chores = ['Wash dishes', 'Mow lawn'];

const newLength = chores.push('Clean room');

console.log(chores);    // ['Wash dishes', 'Mow lawn', 'Clean room']
console.log(newLength); // 3

2. Adding Multiple Elements

You are not limited to adding just one item. You can pass multiple arguments, and they will be added in the order they were provided.

JavaScript
const numbers = [1, 2];
numbers.push(3, 4, 5);

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

3. Merging Two Arrays

If you want to push all elements from one array into another, you can use the Spread Operator (...).

JavaScript
const stack1 = ['a', 'b'];
const stack2 = ['c', 'd'];

stack1.push(...stack2);

console.log(stack1); // ['a', 'b', 'c', 'd']

Note: If you didn’t use the ..., you would end up pushing the entire array as a single element, creating a nested array: ['a', 'b', ['c', 'd']].

4. Pushing an Array into an Array

A common mistake is trying to merge two arrays using .push(). If you push an array into another, it adds the entire array as a single element (creating a nested array).

JavaScript
const snacks = ['chips', 'pretzels'];
const sweets = ['cookies', 'cake'];

snacks.push(sweets); 
// Results in: ['chips', 'pretzels', ['cookies', 'cake']]

The Solution: The Spread Operator (...)

If you want to add the individual elements of one array into another, use the spread operator:

JavaScript
snacks.push(...sweets);
// Results in: ['chips', 'pretzels', 'cookies', 'cake']

Categorized in:

Javascript Array Methods,