How to add an element at the beginning of an array in JavaScript

#javascript #array

Last updated on Nov 15, 2020 by Suraj Sharma



In this tutorial, you will learn how you can add a new element at the beginning of an array in JavaScript.



1. Using Array.unshift() method


The unshift() method adds the value passed as an argument, at the beginning of the calling Array.


const arr = [1,2,3,4,5]

arr.unshift(-1) // returns 6

console.log(arr) // [-1,1,2,3,4,5]

It updates the original Array and returns the length of the array. To prevent updating the original array you can use ES6 Array destructuring, as mentioned below



2. Using Array destructuring


You can use array spread operator (...) and array destructuring to create a new array, with the element added at the beginning


Example:


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

const newArr = [-1, ...arr];

console.log(newArr); // [-1,1,2,3,4,5]

console.log(arr); // [1,2,3,4,5]


Related Solutions



Suraj Sharma is a JavaScript Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.