Categories
JavaScript Answers

How to Declare a JavaScript Array with Objects Inside?

Spread the love

Sometimes, we want to declare a JavaScript array with objects inside.

In this article, we’ll look at how to declare a JavaScript array with objects inside.

Declare a JavaScript Array with Objects Inside

To declare a JavaScript array with objects inside, we can declare an empty array then use a loop to push the objects into an array.

For instance, we can write:

const n = 100;
const sample = [];
for (let i = 0; i < n; i++) {
  sample.push({});
}

to declare the sample array.

Then we use a for loop to loop from 0 to n and in the loop body, we call sample.push with an empty object to add an empty object into an array n times.

Conclusion

To declare a JavaScript array with objects inside, we can declare an empty array then use a loop to push the objects into an array.

Leave a Reply

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