Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to create new objects in runtime in Javascript?

From my colloquial understanding of creating new objects from classes in Javascript one can do the following line of code:

const exampleVariable = new exampleClass("ExampleArguement");

I apologize for this being a novice question but is it possible to create new objects within the execution of the program? Sort of "automating" the creation of objects in my code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Let’s say I need to create 100 objects.

I could technically write 100 lines initializing variables and their respective objects but I am 100% sure there is a more efficient way of doing this.

I tried looking up a solution but I couldn’t quite get the phrasing right so I would appreciate it if someone pointed me in the right direction.

Many thanks.

>Solution :

You can use loops for that.

For example:

class SomeClass{
    constructor(id){
        this.id = id;
    }
}

const objects = [];
const amountOfObjects = 100;
// create objects
for (var i = 0; i < amountOfObjects; i++){
  const object = new SomeClass(i + 1);
  objects.push(object);
}
 
// iterate over the array of objects created and log their id
for (var i = 0; i < objects.length; i++){
  console.log(objects[i].id);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading