Skip to content

Add to array JavaScript

  • by

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>
    const fruits = ['apple', 'banana', 'cherry'];



Add to array JavaScript

Using the length property to add an element to the end of an array

const fruits = ['apple', 'banana', 'cherry'];
fruits[fruits.length] = 'date';

Using the concat() method to create a new array with additional elements

const fruits = ['apple', 'banana', 'cherry'];
const moreFruits = fruits.concat('date', 'elderberry');

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) {
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

Leave a Reply

Your email address will not be published. Required fields are marked *