Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Understanding Array.shift

Array.shift is a function available to arrays that allows us to remove the first element of that array

For example: Lets say we have an array of numbers like this

[1,2,3,4,5]

And we want to get rid of the first number.

We could create a new array that doesn’t contain the first index using a loop.

Heres an example of that

const arr = [1,2,3,4,5];
const newarr = [];
for(let i = 0; i < arr.length; i++) {
   if(i === 0) continue;
   newarr.push(arr[i]);
}

This works but we could get the same result in just one function

The shift() method allows us to remove the first element in our array and if we use it in a variable, get back the value that we removed from the beginning of the array.

So we can simply call arr.shift() for our array of numbers

const arr = [1,2,3,4,5];
arr.shift();
console.log(arr); // returns [2,3,4,5]

If for some reason we needed the value we removed we can set arr.shift() as a variable.

const arr = [1,2,3,4,5];
const removedVal = arr.shift();
console.log(removedVal); // returns 1