Last updated on Nov 15, 2020 by Suraj Sharma
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
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]