How to add an element to beginning of an array

Mo Ibra

Mo Ibra

Jan 1, 2023

In this article we will learn how to add element at beginning of an array in JavaScript.

It is very common to add element at beginning of an array in JavaScript in JavaScript.


Problem

Now we have a problem, which is that we want to add an element at the beginning of the array.

Imagine we have a array like that:

const array = [1, 2, 3, 4, 5];

And we want to add an element at the beginning of this array.

Result will be like this

[0, 1, 2, 3, 4, 5]

How to solve this problem?

In fact, the solution to this problem is very easy, and there is more than one solution to this problem.

  • Using unshift method
  • Using spread operator ...
  • Using concat method.

Add element at beginning using unshift method

We can use unshift method to add an element at the beginning of an array.

Example

// Array
const array = [1, 2, 3, 4, 5];

// Array unshift
array.unshift(0);

// Result:
console.log(array);

Output

[ 0, 1, 2, 3, 4, 5 ]

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


Add element at beginning using spread operator ...

We can use spread operator to solve this problem as well.

Let's see an example

// Array
const array = [1, 2, 3, 4, 5];

// Add element at the beginning of an array
const result = [0, ...array];

// Result:
console.log(result);

Output

[0, 1, 2, 3, 4, 5];

The spread (...) syntax allows an iterable, such as an array or string, to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected. MDN


Add element at beginning using concat method

We can use concat method to solve this problem as well.

// Array
const array = [1, 2, 3, 4, 5];

// Add element at the beginning of an array
const result = [0].concat(array)

// Result:
console.log(result);

Output

[0, 1, 2, 3, 4, 5];

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: