Array.unshift() and Array.shift()

Array.unshift() and Array.shift()

·

2 min read

Hello Everyone! Welcome back to the second article on the Array method series. If you are new to the series, do well to check out the previous article:

Recap

In the first episode of the series, we explained Array.push() which is the method that adds values to the end of the array. And Array.pop() which removes values from the array from the end of the array. They are among the common JavaScript Array methods.

In this episode, we will talk about the unshift() and shift() array methods. Remember that whenever we are dealing with the first and last index of an array, we go with these methods or the push() and pop().

Array.unshift()

This JavaScript array method can be said to be similar to the array.push() method which means it is used to add values. But with the unshift method, it adds values to the beginning of the array. The length of the array will be increased and there is no limit to the number of values we can pass in. Let's have a look at how it works

let arr = ['hashnode', 1, 2,3, false]

arr.unshift('welcome', 'to', 'my', 'blog')

console.log(arr)  // returns ['welcome','to','my','blog', 'hashnode',1,2,3,false]

Array.shift()

This JavaScript array method works like the array.pop() method which means it is used to remove values from an array. It removes an array element from the beginning of the array. It does not pass any argument and decreases the length of the array when called. Let's take a look at the syntax

let arr = ['hashnode', 1, 2,3, false]

arr.shift()

console.log(arr) // returns [1,2,3,false]

References

MDN Docs

Thanks for reading and please share if it is helpful. Feel free to ask any questions in the comments below if you're unsure of any concept. Cheers!