**shift()** removes the element at index 0 and moves every other element one position down. It's O(n) — slower than **pop()** (O(1)) because every element must be re-indexed. Together with **push()**, it creates a **queue** (FIFO — First In, First Out).
1Understanding Array.shift()
shift() removes the element at index 0 and moves every other element one position down. It's O(n) — slower than pop() (O(1)) because every element must be re-indexed. Together with push(), it creates a queue (FIFO — First In, First Out).
shift() is O(n) because it re-indexes the entire array. For large queues, consider a deque (double-ended queue) data structure.
// Queue implementation
const queue = [];
queue.push('task1');
queue.push('task2');
queue.push('task3');
console.log(queue.shift()); // 'task1' (FIFO)
console.log(queue.shift()); // 'task2'
console.log(queue); // ['task3']2Practical Example
Here is a real-world application of Array.shift() showing how it is used in production JavaScript code.
// Non-mutating first removal with slice
const arr = ['a', 'b', 'c', 'd'];
const [head, ...tail] = arr; // destructuring
console.log(head); // 'a'
console.log(tail); // ['b', 'c', 'd']
console.log(arr); // ['a','b','c','d'] unchanged3Best Practices
Follow these guidelines when working with Array.shift():
1. Use push()/shift() for FIFO queue patterns
2. Avoid shift() on large arrays in performance-critical code
3. Use slice(1) for non-mutating removal of first element
Tip: shift() is O(n) because it re-indexes the entire array. For large queues, consider a deque (double-ended queue) data structure.
// Queue implementation
const queue = [];
queue.push('task1');
queue.push('task2');
queue.push('task3');
console.log(queue.shift()); // 'task1' (FIFO)
console.log(queue.shift()); // 'task2'
console.log(queue); // ['task3']