How to Remove the First Element of an Array in JavaScript

JavaScript How to Remove the First Element of an Array

To remove the first element of an array in JavaScript, use the 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.

For example:

var nums = [1, 2, 3]

const n = nums.shift()

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

Output:

Removed 1 from an array

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

For example:

var nums = [1, 2, 3]

nums.pop()

console.log(nums)

Result:

[1, 2]

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

100 JavaScript Interview Questions

50 Buzzwords of Web Development

Share on facebook
Facebook
Share on google
Google+
Share on twitter
Twitter
Share on linkedin
LinkedIn
Share on pinterest
Pinterest