Here are some ways that you can add more data to an array in JavaScript.
1. Use array push()
Array push() allows you to add new items to the end of the array
Examples below:
Add an item
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
superCars.push("Aston Martin");
console.log(superCars);
Add multiple items
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
superCars.push("Aston Martin", "Bugatti");
console.log(superCars);
2. Use array unshift()
Array unshift() allows you to add new items to the beginning of the array
Examples below:
Add an item
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
superCars.unshift("Aston Martin");
console.log(superCars);
Add multiple items
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
superCars.unshift("Aston Martin", "Bugatti");
console.log(superCars);
3. Use Spread syntax(…)
Spread syntax(…) allows the array to expand. However, not within the array itself. It takes the old array and creates a new one with the new items added.
Unlike push() or unshift(), with Spread syntax(…), you are able to add items at either end of an array.
Example below:
Add items at beginning
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
const newSuperCars = [
"Aston Martin",
"Bugatti",
...superCars
];
Add items at end
const superCars = ["McLaren", "Ferrari", "Lamborghini", "Audi R8"];
const newSuperCars = [
...superCars,
"Aston Martin",
"Bugatti"
];