Clue Mediator

Add an item at the beginning of an array in JavaScript

📅January 10, 2022

Today we will show you how to add an item at the beginning of an array in JavaScript. In this article, we will show you three different ways to prepend items to an array.

Checkout more articles on JavaScript

Ways to add an item at the beginning of an array

  1. Using unshift() method
  2. Using spread operator
  3. Using concat() method

1. Using unshift() method

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

var colours=["Black"];

colours.unshift("Blue");
// Output:  ["Blue","Black"]

colours.unshift("Yellow","Orange");
// Output: ["Yellow","Orange","Blue","Black"]

You may like this article: Push, Pop, Shift and Unshift Array Methods in JavaScript

2. Using spread operator

We can achieve the same thing using the Spread Operator.

let arr1 = ['A', 'B', 'C'];
let arr2 = ['A0', ...arr1];
console.log(arr2);
// Output: ['A0', 'A', 'B', 'C']

3. Using concat() method

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

let arr1 = ['A', 'B', 'C'];
let arr2 = ['A0'].concat(arr1);
console.log(arr2);
// Output: ['A0', 'A', 'B', 'C']

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂