Array shift() and unshift()
Quick answer
Shift removes the first array value; unshift inserts values before the current first value. Both change the original array and can change many indices.
How it works
items.shift() returns the removed first value or undefined when empty. items.unshift(a, b) inserts a followed by b and returns the new length. Do not infer guaranteed runtime complexity from the specification alone.
const queue = ["B", "C"];console.log(queue.unshift("A"), queue[0]);console.log(queue.shift(), queue[0]);Expected output in Node.js:
3 AA BAdding at the beginning shifts existing positions; removal restores B as first.
const a = [3];a.unshift(1, 2);console.log(a[0], a[1], a[2]);Expected output in Node.js:
1 2 3Arguments keep their order in a single unshift call.
Common mistakes
Repeated unshift calls are not the same as one call with multiple arguments. Avoid using repeated shift as a blanket performance recommendation for large queues.
Practice
Model a waiting line with push and shift. Predict the next person served.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array shift() and unshift() — Knowledge Check
Apply the taught concept and reason about the result.
Which method removes the first array value?
What does [4].unshift(1,2) return?
After const a=[4]; a.unshift(1,2); what is a[0]?
What does [].shift() return?
Which pair models enqueue at the end and dequeue from the beginning?