Add an element from an array in JavaScript
In JavaScript, there are a few ways to add an element to an array. Depending on whether you want to add an element to the start or the end, or even in the middle.
Using Array.push() or Array.unshift() to add elements to the array
With Array.push()
you add an item to the end of an array,
and with Array.unshift()
you add an item to the begin of the array.
const cities = ['Stormwind', 'Orgrimmar', 'Ironforge', 'Thunder Bluff'];
cities.push('Dalaran')
console.log(cities) // ['Stormwind', 'Orgrimmar', 'Ironforge', 'Thunder Bluff', 'Dalaran']
cities.unshift('Gnomeregan')
console.log(cities) // ['Gnomeregan', 'Stormwind', 'Orgrimmar', 'Ironforge', 'Thunder Bluff', 'Dalaran']
Using Array.splice() and Array.toSpliced() to add an item in a specific space
Array splice can be used to remove an item, but we can also use it to add something. It takes 3 arguments, the first one being where to start inserting, the second argument is how many items we want to delete (so we use 0), and then you can add as many items as you like to insert.
const ores = [
'tin' ,
'copper',
'iron',
'mithril',
];
ores.splice(3, 0, 'coal');
console.log(ores); // ['tin', 'copper', 'iron', 'coal', 'mithril']
With Array.toSpliced()
we can do the same thing, but it won’t change the original array, and instead it returns a new one:
const ores = [
'tin' ,
'copper',
'iron',
'mithril',
];
console.log(ores.toSpliced(3, 0, 'coal')); // ['tin', 'copper', 'iron', 'coal', 'mithril']
// Still the same
console.log(ores); // ['tin', 'copper', 'iron', 'mithril']
Using array destructuring
To add something to the begin or the end of an an array, we can use destructuring to create a new array.
const names = ['Harry', 'Ron', 'Hermione'];
console.log(['Harid', ...names]) //['Hagrid','Harry', 'Ron', 'Hermione']
// Still the same
console.log(names) //['Harry', 'Ron', 'Hermione']
console.log([...names, 'Hagrid']) //['Harry', 'Ron', 'Hermione', 'Hagrid']
// Still the same
console.log(names) //['Harry', 'Ron', 'Hermione']
If you want to get notified of the next blog post, join the newsletter.