How to fill arrays with data with JavaScript?

Estimated read time 1 min read

There are many ways to fill arrays with data in JavaScript. Here are a few common methods:

  1. Using a for loop:
const arr = [];
for (let i = 0; i < 10; i++) {

In this example, an empty array arr is created and then filled with data using a for loop that pushes the values from 0 to 9 onto the end of the array.

  1. Using the Array.from() method:
const arr = Array.from({length: 10}, (_, i) => i);

In this example, an array arr is created using the Array.from() method and a mapping function that returns the index i for each element.

  1. Using the spread operator:
const arr = [...Array(10).keys()];

In this example, an array arr is created using the spread operator and the Array() constructor with the keys() method. This creates an array with 10 elements, ranging from 0 to 9.

These are just a few examples of how you can fill an array with data in JavaScript. You can also use other methods, such as the map() method or the fill() method, to fill an array with data.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply