How to Remove the First Element of an Array in JavaScript

Remove first element with shift(). Remove last with pop().

To remove the first element of an array in JavaScript, use the built-in shift() function.

For example, let’s return number 1 from this array of numbers:

var nums = [1, 2, 3]

nums.shift()

console.log(nums)

Result:

[2, 3]

Notice that shift() also returns the removed element. This is useful if you want to use it later. To use this returned element, store it into a variable when removing it.

For example, let’s remove the first element of an array of numbers and store the removed element in a variable:

var nums = [1, 2, 3]

const n = nums.shift()

console.log(`Removed ${n} from an array`)

Running this piece of code produces the following output:

Removed 1 from an array

If you’re a beginner in JavaScript, you might be confused because of this code line const n = nums.shift(). To clarify, this piece of code does two things at the same time:

  1. It removes the first element of the array.
  2. It stores the removed first element into a variable.

How to Remove the Last Item of an Array in JavaScript?

Similar to how you might want to remove the first element of an array in JavaScript, you might want to pop out the last one.

To remove the last item of an array, use the pop() function.

For example:

var nums = [1, 2, 3]

nums.pop()

console.log(nums)

The result of this code is an array like this:

[1, 2]

Notice that the pop() function also returns the removed element. This might be useful in case you want to use the removed element later on in your code.

Conclusion

  • To remove the first element of an array in JavaScript, use the shift() function.
  • To remove the last element of an array, use the pop() function.

Thanks for reading. I hope you find it useful.

Happy coding!

Further Reading