Javascript Tutorial to Add new Array Elements at Beginning of Array Using unshift() Method

 

 

 

const array = [3, 2, 1]

const newFirstElement = 4

const newArray = [newFirstElement].concat(array) // [ 4, 3, 2, 1 ]

console.log(newArray);

 

concat can also append items. The arguments to concat can be of any type; they are implicitly wrapped in a single-element array, if they are not already an array:

const array = [3, 2, 1]

const newLastElement = 

// Both of these lines are equivalent:
const newArray1 = array.concat(newLastElement) // [ 3, 2, 1, 0 ]
const newArray2 = array.concat([newLastElement]) // [ 3, 2, 1, 0 ]

console.log(newArray1);
console.log(newArray2);

 

See also  Node.js Microsoft OneDrive API Module to Upload & Download Images to Storage in Browser Using Javascript Full Project For Beginners

 

var a = [23, 45, 12, 67];
a.unshift(34);
console.log(a); // [34, 23, 45, 12, 67]

 

 

With ES6 , use the spread operator ... :

DEMO

var arr = [23, 45, 12, 67];
arr = [34, ...arr]; // RESULT : [34,23, 45, 12, 67]

console.log(arr)

Leave a Reply