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.
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
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
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.