**unshift()** is the inverse of **shift()**. It inserts elements at the front (index 0) and shifts existing elements to higher indices. This is O(n) due to re-indexing. It returns the **new length**. For non-mutating prepend, use spread: `[newItem, ...arr]`.
1Understanding Array.unshift()
unshift() is the inverse of shift(). It inserts elements at the front (index 0) and shifts existing elements to higher indices. This is O(n) due to re-indexing. It returns the new length. For non-mutating prepend, use spread: [newItem, ...arr].
unshift() is O(n) just like shift(). For large arrays with frequent prepends, prefer a data structure designed for it.
const queue = ['b', 'c', 'd'];
queue.unshift('a');
console.log(queue); // ['a', 'b', 'c', 'd']
// Multiple items (maintains order)
queue.unshift('x', 'y', 'z');
console.log(queue); // ['x','y','z','a','b','c','d']2Practical Example
Here is a real-world application of Array.unshift() showing how it is used in production JavaScript code.
// Non-mutating prepend
const original = [3, 4, 5];
const prepended = [1, 2, ...original];
console.log(original); // [3, 4, 5] unchanged
console.log(prepended); // [1, 2, 3, 4, 5]3Best Practices
Follow these guidelines when working with Array.unshift():
1. Use [newItem, ...arr] for non-mutating prepend
2. Use unshift with multiple items: arr.unshift(a, b) vs two calls
3. Prefer spread or concat for functional programming style
Tip: unshift() is O(n) just like shift(). For large arrays with frequent prepends, prefer a data structure designed for it.
const queue = ['b', 'c', 'd'];
queue.unshift('a');
console.log(queue); // ['a', 'b', 'c', 'd']
// Multiple items (maintains order)
queue.unshift('x', 'y', 'z');
console.log(queue); // ['x','y','z','a','b','c','d']