This article will show you how to add new item at the beginning of an array in JavaScript. There are several approaches to add a new first item to an array in JavaScript, each with a description and complete code example are given below:
1. Using Array.unshift() Method
Using the unshift()
method to add an item to the beginning of an array.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; array.unshift(newItem); // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(array);
2. Using Array.slice() Method
Using the slice()
method to create a new array with the new item at the beginning.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; const newArray = [newItem, ...array]; // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
3. Using Array.concat() Method
Using the concat()
method to concatenate an array with a new item array.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; const newArray = [].concat(newItem, array); // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
4. Using Spread Operator with Array Literal
Using the spread operator with an array literal to create a new array with the new item at the beginning.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; const newArray = [newItem, ...array]; // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
5. Using Array.slice() with for Loop
Using the slice()
method along with a for
loop to create a new array with the new item at the beginning.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; const newArray = [newItem]; for (let i = 0; i < array.length; i++) { newArray.push(array[i]); } // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
6. Using Array.from() Method
Using the Array.from()
method to create a new array from an iterable, with the new item at the beginning.
const array = ['Banana', 'Orange', 'Grapes', 'Mango']; const newItem = 'Apple'; const newArray = Array.from([newItem, ...array]); // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(newArray);
7. Using Array.unshift() in a Function
Creating a function to encapsulate the logic of adding a new first item to an array using unshift()
.
function addFirstItem(array, newItem) { array.unshift(newItem); } const fruits = ['Banana', 'Orange', 'Grapes', 'Mango']; const newFruit = 'Apple'; addFirstItem(fruits, newFruit); // Output: [ 'Apple', 'Banana', 'Orange', 'Grapes', 'Mango' ] console.log(fruits);