JavaScriptArrays
Array. prototype. shift()
Removes the first element of an array and returns it.
- Returns
- The removed first element, or
undefined. - Changes the original
- Yes
Example
#JavaScript
const queue = ['Emma', 'Jack', 'Mia']
const next = queue.shift()
console.log(next)
console.log(queue)Console
Emma
['Jack', 'Mia']
Definition and usage
#The shift() method takes out the array’s first element, shifts the rest one position to the left, and returns the removed element. On an empty array it returns undefined.
Together with push(), it lets you use an array like a queue: the first item added comes out first, just like a checkout line.
Shifting every element costs time, so with very large arrays and frequent shift() calls, it can get slow.
Syntax
#Syntax
array.shift()Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- To read the first element without removing it,
array[0]is enough. - A non-mutating version:
const rest = queue.slice(1)orconst [first, ...rest] = queue.
Related entries
#- Array.prototype.unshift()Adds elements to the start of an array and returns its new length.
- Array.prototype.pop()Removes the last element of an array and returns it.
- Array.prototype.push()Adds elements to the end of an array and returns its new length.
- DestructuringDestructuring pulls values out of arrays and objects straight into separate variables.
Spotted a mistake or missing an example? Write to us.