What is the push() method in Javascript?

The push() method adds one or more elements to the end of the array and returns the length of the array.

The push() method will mutate the original array. Let’s look at some examples to demonstrate the use of push.

let numbers = [1, 2, 3, 4, 5];

let count = numbers.push(6);

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

When you push value 6 in the array numbers, this new value will be added at the end of the array.

Notice that, if you assign the push method to a variable, it will hold the array’s length and not the array itself. Hence, in this example, count will contain the value 6 which is the length of the array numbers.

Adding multiple elements using push() method

When using push() method you can add one or more elements to an array. Simply specify all the elements as arguments to the push() method.

let numbers = [1, 2, 3, 4, 5];

numbers.push(6, 7, 8, 9);

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

Merge two arrays using push() method

We can make use of the spread method to merge two arrays along with the push method.

let arr1 = [1, 2, 3, 4, 5];
let arr2 = [6, 7, 8, 9];

arr1.push(...arr2);

console.log(arr1); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

push objects in an array

const employees = [
    {
        fName: 'Mickey',
        lName: 'Mouse'
    },
    {
        fName: 'Donald',
        lName: 'Duck'
    }
];

const emp = {
    fName: 'Minnie',
    lName: 'Mouse'
};

employees.push(emp);

console.log(employees);

// Output: 
[
    {
        "fName": "Mickey",
        "lName": "Mouse"
    },
    {
        "fName": "Donald",
        "lName": "Duck"
    },
    {
        "fName": "Minnie",
        "lName": "Mouse"
    }
]

We have an array of objects employees. To push the emp object in the employees array we make use of the push() method.

What is the pop() method in Javascript?

The pop() method deletes the last element from the array and returns that element.

The pop() method will mutate the original array. Let’s look at some examples to demonstrate the use of pop.

let numbers = [1, 2, 3, 4, 5];

let element = numbers.pop();

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

In the above example, the pop() method will remove the last element that is 5 from the array numbers. When you assign a variable to the pop() method, it will store the deleted element. In this case, it is the element 5.

Every time you call the pop() method it will remove the last element.

let numbers = [1, 2, 3, 4, 5];

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

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

numbers.pop();
console.log(numbers); // [1, 2]

numbers.pop();
console.log(numbers); // [1]