shift()
function. The shift() method changes the length of an array. The array shift()
method returns the removed element of an array. The shift()
method shifts everything to the left. 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. If you wish to use it later, this is helpful. When removing this returned element, save it in a variable so that you can use it later.
Let’s take the first element of a number array as an illustration and remove it, storing the removed element in a variable:
var nums = [1, 2, 3]
const n = nums.shift()
console.log(`Removed ${n} from an array`)
The output of running this code is as follows:
Removed 1 from an array
If you’re new to JavaScript, the code line const n = nums.shift () can be confusing to you. 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?
The last element of an array may need to be removed, much like how you might want to pop out the first one in JavaScript.
To remove the last item of an array, use the pop() function.
Example:
var nums = [1, 2, 3]
nums.pop()
console.log(nums)
The result of this code is an array like this:
[1, 2]
It is important to note that the pop() function also returns the removed element. In the event that you decide to reuse the deleted element in your code in the future, this could be helpful.
Wrap up
- 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. Happy coding!