
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:
- It removes the first element of the array.
- 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
About the Author
- I'm an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Artificial Intelligence2023.05.16Humata AI Review (2023): Best PDF Analyzer (to Understand Files)
Python2023.05.139 Tips to Use ChatGPT to Write Code (in 2023)
Artificial Intelligence2023.04.1114 Best AI Website Builders of 2023 (Free & Paid Solutions)
JavaScript2023.02.16How to Pass a Variable from HTML Page to Another (w/ JavaScript)