How to Add Element at Beginning of an Array in JavaScript How to Add Element at Beginning of an Array in JavaScript

Page content

In this tutorial, we’ll learn different ways of adding new elements at the beginning of an Array in JavaScript.

Using Array.unshift

The easiest way to add elements at the beginning of an array is to use unshift() method.

var fruits = ["Apple", "Banana", "Mango"];

fruits.unshift("Orange");
console.log(fruits);
// Prints ["Orange", "Apple", "Banana", "Mango"]

fruits.unshift("Guava", "Papaya");
console.log(fruits);
// Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]

It adds the elements of your original array. Sometime you wish not to alter the original array, and assign it to a new variable instead.

In Javascript, you can do this in multiple ways in a single statement.

Using Spread Operator (…)

We can use spread operator ... to make a copy of an array. It’s short syntax is very handy.

var fruits = ["Apple", "Banana", "Mango"];

var moreFruits = ["Orange", ...fruits];
console.log(moreFruits);
// Prints ["Orange", "Apple", "Banana", "Mango"]

var someoMoreFruits = ["Guava", "Papaya", ...moreFruits];
console.log(someoMoreFruits);
// Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]

console.log(fruits);
// Prints ["Apple", "Banana", "Mango"]

New elements are added at the beginning followed by copy of the original Array (using ...) and assigned to a new variable.

We see that our original array remains the same.

Using Array.concat

We can also user concat() method to join two (or more) arrays at the beginning.

var fruits = ["Apple", "Banana", "Mango"];
var moreFruits = ["Orange"];
var someoMoreFruits = ["Guava", "Papaya"];

var allFruits = someoMoreFruits.concat(moreFruits, fruits);
console.log(allFruits);
// Prints ["Guava", "Papaya", "Orange", "Apple", "Banana", "Mango"]