How to Populate a JavaScript Array?

Estimated read time 1 min read

There are several ways to populate a JavaScript array:

  1. Add elements one by one using the array’s push() method:
let myArray = [];
  1. Use an array literal to define the elements when creating the array:
let myArray = ["element1", "element2"];
  1. Use a loop to add elements to the array:
let myArray = [];
for (let i = 0; i < 5; i++) {
  myArray.push("element" + i);
  1. Use the array’s splice() method to insert new elements at a specific index:
let myArray = ["element1", "element3"];
myArray.splice(1, 0, "element2");

This will insert “element2” at index 1 of the array.

  1. Use the array’s concat() method to merge two or more arrays:
let myArray1 = ["element1", "element2"];
let myArray2 = ["element3", "element4"];
let myArray = myArray1.concat(myArray2);

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply