Array Unshift in JavaScript
Mar 4, 2022
The unshift()
function adds one or more elements to the beginning of the array and returns the new length of the array.
const array = [3, 4, 5];
array.unshift(1, 2); // 5
array; // 1, 2, 3, 4, 5
Unshifting an Array
If you want to unshift an array, unshift([1, 2])
will add [1, 2]
as the first element of the array.
unshift()
does not flatten arrays.
const array = [3, 4, 5];
array.unshift([1, 2]); // 4
array; // [[1,2], 3, 4, 5]
If you want to unshift the elements of an array, you should use the spread operator as shown below.
const array = [3, 4, 5];
const array2 = [1, 2];
array.unshift(...array2); // 5
array; // 1, 2, 3, 4, 5
More Fundamentals Tutorials
- How to Add 2 Arrays Together in JavaScript
- The String `match()` Function in JavaScript
- Convert a Set to an Array in JavaScript
- What Does Setting the Length of a JavaScript Array Do?
- Get the Last Element in an Array in JavaScript
- Skip an Index in JavaScript Array map()
- Conditionally Add an Object to an Array in JavaScript