unshift() adds one or more elements to the beginning of a JavaScript array. It mutates the original array, moves existing values to higher indexes, and returns the new length.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
const newLength = scripts.unshift("VBScript", "Perl");
console.log(scripts); // ["VBScript", "Perl", "PHP", "ASP", "JavaScript", "HTML"]
console.log(newLength); // 6
array.unshift(element1);
array.unshift(element1, element2, element3);
The return value is the new array length, not the modified array.
const languages = ["JavaScript", "Python"];
languages.unshift("PHP");
console.log(languages); // ["PHP", "JavaScript", "Python"]
const values = [4, 5, 6];
values.unshift(1, 2, 3);
console.log(values); // [1, 2, 3, 4, 5, 6]
Multiple values passed in one call keep their argument order. Repeated single-value calls reverse the order of those newly inserted values.
const first = [4, 5, 6];
first.unshift(1, 2, 3);
console.log(first); // [1, 2, 3, 4, 5, 6]
const second = [4, 5, 6];
second.unshift(1);
second.unshift(2);
second.unshift(3);
console.log(second); // [3, 2, 1, 4, 5, 6]
The original page demonstrated that numeric keys change when values are inserted at index 0.
const scripts = ["PHP", "ASP", "JavaScript", "HTML"];
scripts.unshift("VBScript", "Perl");
for (const [index, value] of scripts.entries()) {
console.log(index, value);
}
0 VBScript
1 Perl
2 PHP
3 ASP
4 JavaScript
5 HTML
const values = [2, 3];
const alias = values;
values.unshift(1);
console.log(alias); // [1, 2, 3]
const values = [3, 4];
const prefix = [1, 2];
values.unshift(prefix);
console.log(values); // [[1, 2], 3, 4]
Use spread syntax when you want the prefix array's elements inserted individually:
const values = [3, 4];
const prefix = [1, 2];
values.unshift(...prefix);
console.log(values); // [1, 2, 3, 4]
const original = [3, 4];
const combined = [1, 2, ...original];
console.log(original); // [3, 4]
console.log(combined); // [1, 2, 3, 4]
Use push() when values should be added to the end, or splice() for a specific position.
unshift() adds to the beginning.array = array.unshift(value) and replacing the array with its length.unshift() repeatedly and overlooking the reversed insertion order.unshift(otherArray) to flatten that array.Add at the End with push() Add at Any Position with splice() Display Array Elements Array Reference
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.