To add elements to an array in JavaScript, you can use the push()
method or the length
property. Both of these methods modify the original array.
array.push(element1, element2, ..., elementN)
// OR
array[array.length] = element;
If you want to create a new array with additional elements, you can use the spread operator ...
or the concat()
method.
Add to array JavaScript example
Simple example code using the push()
method to add an element to the end of an array.
<!DOCTYPE html>
<html>
<body>
<script>
const fruits = ['apple', 'banana', 'cherry'];
fruits.push('date');
console.log(fruits);
</script>
</body>
</html>
Output:
Using the length
property to add an element to the end of an array
const fruits = ['apple', 'banana', 'cherry'];
fruits[fruits.length] = 'date';
console.log(fruits);
Using the concat()
method to create a new array with additional elements
const fruits = ['apple', 'banana', 'cherry'];
const moreFruits = fruits.concat('date', 'elderberry');
console.log(moreFruits);
Using a loop to add the first 5 even numbers to an array:
const evenNumbers = [];
for (let i = 0; evenNumbers.length < 5; i++) {
if (i % 2 === 0) {
evenNumbers.push(i);
}
}
console.log(evenNumbers); // [0, 2, 4, 6, 8]
Do comment if you have any doubts or suggestions on this Js array topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version