Add New Elements to the Beginning of an Array with JavaScript unshift

Web Dev
Sponsored links

In this article, I will introduce how to add new elements to the beginning of an array with JavaScript unshift.

The unshift() method

The unshift() method adds new elements to the beginning of the array and returns the number of elements in the array to which the element was added.

The syntax is below.

arr.unshift(element1[, ...[, elementN]])

For example, if you want to add "apple" to the beginning of the array called "art", it will be as follows.

let arr = ["orange", "lemon"];

console.log(arr.unshift("apple")); // 3
console.log(arr); // ["apple", "orange", "lemon"]

If multiple elements are passed as arguments, they will be added to the beginning of the array in exactly the same order as they were passed as arguments.
Calling this method n times using a loop etc., will not return same results.

let arr = ["orange", "lemon"];

console.log(arr.unshift("apple", "banana")); // 4
console.log(arr); // ["apple", "banana", "orange", "lemon"]

arr = ["orange", "lemon"]; // Reset
console.log(arr.unshift(["apple", "banana"])); // 3

console.log(arr); // [["apple", "banana"], "orange", "lemon"]

arr = ["orange", "lemon"]; // Reset
console.log(arr.unshift("apple")); // 3
console.log(arr.unshift("banana")); // 4

console.log(arr); // ["banana", "apple", "orange", "lemon"]