shift()

ES3+

Removes the first element from an array and returns that element.

Syntax

array.shift()

Return Value

any

The removed element

Examples

JavaScript
const fruits = ['apple', 'banana', 'cherry'];
const first = fruits.shift();
console.log(first);
console.log(fruits);
Output:
// 'apple' ['banana', 'cherry']

📌 When to Use

Use shift() when you need to remove and retrieve the first element from an array. It's essential for implementing queues (FIFO), processing items in order, or consuming elements from the beginning.

⚠️ Common Mistakes

Using shift() in performance-critical code with large arrays - it's O(n), not O(1)

Forgetting that shift() modifies the original array

Using shift() when you only need to read the first element - use arr[0] instead

✅ Best Practices

For high-performance queues, consider using an object with head/tail indices instead

For immutable operations, use slice: const [first, ...rest] = arr or arr.slice(1)

Use push/shift together to implement a queue (FIFO) data structure

⚡ Performance Notes

shift() is O(n) because all remaining elements must be re-indexed. For large arrays or frequent operations, this can be slow. Consider using a linked list or a circular buffer for high-performance queue implementations.

🌍 Real World Example

Processing a Message Queue

Process messages in FIFO order from a queue

const messageQueue = [];

function addMessage(message) {
  messageQueue.push(message);
}

function processNextMessage() {
  if (messageQueue.length === 0) {
    return null;
  }
  const message = messageQueue.shift();
  handleMessage(message);
  return message;
}

// Usage
addMessage({type: 'email', to: 'user@example.com'});
addMessage({type: 'sms', to: '+1234567890'});
processNextMessage();  // Processes email first (FIFO)

Related Methods