Array.unshift in JavaScript: A Practical Guide
A comprehensive guide to array unshift in javascript, showing how to prepend elements to the front, what it returns, and how to implement immutable patterns when needed.

The array unshift in javascript method adds one or more elements to the front of an array and returns the new length. It mutates the original array, making it ideal for in-place updates, but something to watch for in functional programming patterns. This quick definition leads into deeper, practical examples.
What is array unshift in javascript?
In this section, we explore the core concept behind the array unshift in javascript, focusing on how it prepends elements to the start of an existing array. Understanding this behavior is essential when managing stateful data in front-end applications. The keyword we focus on is the exact phrase you'll see throughout examples: array unshift in javascript. The operation mutates the original array, which means references to that array will reflect changes immediately.
let numbers = [2, 3, 4];
let newLength = numbers.unshift(1);
console.log(numbers); // [1, 2, 3, 4]
console.log(newLength); // 4This first example shows a single-value prepend. You can prepend multiple values in one call, and the array itself is updated in place. As a rule of thumb, prefer explicit mutations when you need performance, and consider immutability patterns when your program relies on predictable state changes.
let colors = ['green'];
colors.unshift('red', 'blue');
console.log(colors); // ['red', 'blue', 'green']-bearing the idea that unshift mutates the source array, you can apply it to scenarios like prepending headers, priorities, or padding values during iterative processing.
How unshift differs from push and spread
To make the behavior crystal clear, compare unshift with push and the spread syntax as an immutability-friendly alternative. While push adds to the end of an array (and also mutates it), unshift adds to the front, which changes indexing for all elements. Spread syntax, on the other hand, lets you create a new array without mutating the original one.
let a = [2, 3];
a.unshift(1); // mutates a: [1, 2, 3]
console.log(a); // [1, 2, 3]
let b = [2, 3];
b.push(4); // mutates b: [2, 3, 4]
console.log(b); // [2, 3, 4]
let c = [2, 3];
let d = [0, ...c]; // immutability-friendly: creates a new array
console.log(c); // [2, 3]
console.log(d); // [0, 2, 3]If you need to prepend while preserving the original array for other parts of your code, prefer the spread approach to create a new array instead of mutating in place.
Return value and side effects
The unshift method returns the new length of the array after prepending. This can be useful for quick checks but should not be confused with a value representing the inserted elements. Remember that the operation mutates the array in place, so all references to the original array reflect the change.
let arr = [10, 20, 30];
let updatedLen = arr.unshift(-5, -4);
console.log(arr); // [-5, -4, 10, 20, 30]
console.log(updatedLen); // 5In functional programming or Redux-like patterns, you would avoid mutating state, opting for a new array construction instead of unshift.
Practical examples with numbers
Numbers are a common use case for unshift when you want to build a sequence from the front. You can prepend a single value or multiple values with one call. The example below demonstrates both approaches and shows how indexing changes as elements are added.
let seq = [2, 3, 4];
seq.unshift(1); // prepend a single value
console.log(seq); // [1, 2, 3, 4]
let extended = [0, ...seq]; // immutably preprend using spread
console.log(extended); // [0, 1, 2, 3, 4]The spread variant does not mutate the original array and can be combined with other elements to build complex sequences efficiently.
Practical examples with strings and objects
Unshift is not limited to numbers. It works with any data type, including strings and objects, which is useful for building stacks, queues, or test data. Here are two quick demonstrations.
let fruits = ['banana'];
fruits.unshift('apple', 'orange');
console.log(fruits); // ['apple', 'orange', 'banana']
let users = [{ id: 1 }, { id: 2 }];
users.unshift({ id: 0 });
console.log(users); // [{ id: 0 }, { id: 1 }, { id: 2 }]Using unshift with objects demonstrates that you’re inserting references to objects, not deep clones, which is important for state changes and identity checks.
Immutability and alternatives for functional programming
If you’re aiming for a functional style, mutating arrays with unshift can lead to hard-to-track state changes. The recommended approach is to construct a new array with the desired front elements while keeping the original array intact. The spread syntax is a clean and efficient pattern for this use case.
const original = [2, 3, 4];
const withFront = [1, ...original];
console.log(original); // [2, 3, 4]
console.log(withFront); // [1, 2, 3, 4]You can also wrap this in a small helper to clarify intent in your codebase:
const prepend = (arr, ...values) => [...values, ...arr];
const result = prepend([3, 4], 1, 2);
console.log(result); // [1, 2, 3, 4]These patterns preserve immutability and make reasoning about state changes easier in complex applications.
Common pitfalls and best practices
Even common operations like unshift can trip you up if you’re not careful. Here are a few pitfalls and how to avoid them.
- Passing undefined will insert an undefined element. This is often a source of subtle bugs. Always validate inputs before unshifting.
- Unshifting an array into another array results in a nested array if you don’t spread. Use spread syntax to avoid nesting when prepending multiple values.
- If you rely on the return value for logic, remember it’s the new length, not the inserted values.
let a = [1, 2];
a.unshift(undefined); // [undefined, 1, 2]
console.log(a.length); // 3
let b = [1, 2];
let c = [0, ...b]; // [0, 1, 2]
console.log(c);Consistency in how you mutate arrays across your project reduces bugs and makes code more readable.
Performance considerations and browser differences
Performance of unshift scales with array size because every element is shifted to accommodate new items at the front. In hot code paths where many elements are prepended frequently, consider alternatives that minimize churn, such as building a new array with spread, or using linked data structures in specialized cases. Modern engines handle typical usage well, but large front-loaded arrays may incur reindexing costs.
// Benchmark-style example (conceptual; run in a dev environment)
let large = new Array(100000).fill(0);
console.time('unshift single');
large.unshift(-1);
console.timeEnd('unshift single');
let largeCopy = [ -1, ...large ];
console.time('spread copy');
let cloned = largeCopy.slice();
console.timeEnd('spread copy');When writing performance-critical code, profile with real datasets and consider immutability patterns to avoid repeated reallocation.
Steps
Estimated time: 25-40 minutes
- 1
Plan the data flow
Identify where you need to prepend data and how it affects downstream logic. Decide if you should mutate in place or preserve the original array by using a new array with spread.
Tip: Document the chosen approach to maintain consistency across the codebase. - 2
Implement with unshift in code
Add the unshift call where needed and verify the array content after the operation. Use console.log to confirm the new order and the returned length.
Tip: Log both the array and the return value for clarity. - 3
Test and verify
Run unit tests or manual tests to ensure edge cases (undefined, multiple values) behave as expected. Check that references reflect the mutation if that’s intended.
Tip: Include tests for multiple inserted values and undefined. - 4
Refactor for immutability if needed
If you must avoid mutation, rewrite using spread syntax to build a new array instead of mutating the original.
Tip: Prefer immutability in stateful applications.
Prerequisites
Required
- Required
- Basic knowledge of JavaScript arrays and methodsRequired
Optional
- Code editor (e.g., VS Code)Optional
- Familiarity with console loggingOptional
Keyboard Shortcuts
| Action | Shortcut |
|---|---|
| CopyCopy code or text in editors | Ctrl+C |
| PastePaste into editor or terminal | Ctrl+V |
| UndoRevert last change in editor | Ctrl+Z |
| RedoRedo last undone action | Ctrl+Y |
| Toggle line commentComment or uncomment selected lines | Ctrl+/ |
Questions & Answers
What does Array.unshift do in JavaScript?
Array.unshift adds one or more elements to the front of an array and returns the new length. It mutates the original array, which makes it efficient for in-place updates but requires care in code that expects immutability.
Unshift lets you put things at the start of an array and tells you how long the array is afterward.
Does unshift mutate the original array?
Yes. Unshift mutates the array you call it on, changing the order of elements in place. Any references to that array will reflect the new state.
Yes, it changes the original array in place.
What is the return value of unshift?
The return value is the new length of the array after prepending the new elements. It does not return the added elements themselves.
It returns the new length, not the items you added.
Can unshift insert multiple items at once?
Yes. You can pass multiple arguments to unshift to prepend several values in a single call.
Yes, you can add many items at the front at once.
How does unshift compare to using spread for immutability?
Unshift mutates the original array. If you need immutability, build a new array using spread syntax, e.g., [newFirst, ...arr].
If you want to avoid changing the original array, use spread to create a new one.
What happens if you unshift undefined?
Undefined becomes a value in the array, which can lead to subtle bugs. Validate inputs to avoid unintended elements.
If you pass undefined, it becomes an element in the array.
What to Remember
- Prepend values with one call
- Unshift mutates the original array
- Return value is the new length
- Use spread for immutable patterns
- Prepend multiple values at once