DEV Community


Understanding JavaScript Array Series XIX - Array.shift()

Nedy Udombat
Software Engineer
・2 min read

Yesterday, you asked a question saying That's cool and simple, but what if I want to remove the first element of an array?. Can't recall asking this? Check this article to refresh your memory.

So let's say we have this array [0, 1, 2, 3, 4, 5] and we want to remove the first element of the array what do we do?

Well, we can consult a magician or we can simply call the array.shift() method on the given array.

So you are saying that the Array.shift() method removes the first element of that array and returns the removed element? Yes, I am. Its syntax is similar to the Array.pop() syntax, all you have to do is append .shift() to the array you are working with like this:

const removedElem = arr.shift();

[arr]: This is the array in which whose first element you want to remove.

[elem]: This holds the element that is removed from the array.

Cool, it is kind of similar to array.pop(), except here it removes the element from the beginning of the array. Please, can you show us an example? Sure why not.

const numArray = [0, 1, 2, 3, 4, 5];
const elem = numArray.shift()

console.log(numArray) // [1, 2, 3, 4, 5];
console.log(elem) // 0

Just like the array.pop() method, no argument is required and the original array is mutated.

Let me guess if the array is empty this method returns undefined right? Yes, correct!

const emptyArray = [];
const elem = emptyArray.shift()

console.log(elem) // undefined

I am glad you are learning buddy. Do you have any questions for me?

Yes Yes, what if I want to put back the element I have removed either from the start of the array or the end of the array?

Good question. You can look into the Array.unshift() and the Array.push() method, we will talk about them tomorrow.

That's all for today, See you next time!!! 😆 😁

Thank you for reading. 👍

Discussion (0)