What is the unshift() method in Javascript?

The unshift() method adds one or more elements to the beginning of an array and returns the length of the array.

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

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

let count = numbers.unshift(100);

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

When you unshift value 100 in the array numbers, this new value will be added at the beginning of the array.

Notice that, if you assign the unshift 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 unshift() method

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

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

let count = numbers.unshift(100, 200);

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

Merge two arrays using unshift() method

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

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

arr1.unshift(...arr2);

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

unshift objects in an array

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

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

employees.unshift(emp);

console.log(employees);

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

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

What is the shift() method in Javascript?

The shift() method deletes the first element from the array and returns that element.

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

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

let element = numbers.shift();

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

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

Every time you call the shift() method it will remove the first element.

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

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

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

numbers.shift();
console.log(numbers); // [4, 5]

numbers.shift();
console.log(numbers); // [5]