Using the Splice method

Add an item to the start of an array.

const colours = ['yellow', 'red'] 
colours.splice(0, 0, 'blue')
console.log(colours); // ['blue', 'yellow', 'red']

Using the spread operator

There are no mutations with this code.

function addItem(items, itemToAdd) { 
   return [...Items, itemToAdd];

Using the unshift method

The unshift method adds new items to the beginning of an array, and returns the new length
This example will mutate the original array.

function addItem(items, itemToAdd) { 
   return Items.unshift(itemToAdd);

© 2023 Better Solutions Limited. All Rights Reserved. © 2023 Better Solutions Limited TopPrevNext