Instances of object

why do we need to create instances of objects in javascript

Can you give us a code example of what you are asking?

From my understanding, Class is a template from which we can create multiple instances of objects.

There are some native objects like Date, Promise, Map etc., where we are creating instances of this objects. why do we need to create instances, can’t we use them directly like Math object.

A typical class holds both data and methods to manipulate that data. You need to create an object from the class in order to store data in it. For example, how are you going to store data in a Map if you don’t have a name for it so you can refer to it throughout your code. That’s why you have to instantiate a new Map object and save it to a variable, so you can access it again at a later time.

Now there are things called static methods in classes that allow you to use the method of a class without creating an object, which is what you are referring to with the methods of the Math class. It wouldn’t really make sense to create a Math object. The Math class is purely intended to provide mathematical functions, not store data for later use.

And there are classes that can do both. You can create a new object from them or you can call static methods from them directly. The Date class is one example.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.