// Use unshift method if you don't mind mutating issue
// If you want to avoid mutating issue
const array = [3, 2, 1]
const newFirstElement = 4
const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]
console.log(newArray);
let newLength = fruits.unshift('Strawberry') // add to the front
// ["Strawberry", "Banana"]
In JavaScript, you use the unshift() method
to add one or more elements to the beginning
of an array and it returns the array's
length after the new elements have been added.
example:
var colors = ['white', 'blue'];
colors.unshift('red');
console.log(colors);
// colors = ['red', 'white', 'blue']
var numbers = [2, 3, 4, 5];
numbers.unshift(1);
console.log(numbers);
// numbers: [ 1, 2, 3, 4, 5 ]
var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]
console.log(arr)
Array.splice(position,0,new_element_1,new_element_2,...);
Code language: JavaScript (javascript)