why Date need ‘new’ keyword to create Date object and ObjectId or BinData etc. do not need ‘new’ keyword? I was hoping for consistency.
Hey @ajinkya_shidhore1,
Welcome to the MongoDB Community!
The Date object is a built-in constructor in JavaScript, and when you create a Date object, you use the “new” keyword to call the constructor.
The
Dateconstructor function requires the use of the “new” keyword because it creates an instance of the “Date” class.
- When called as a constructor like
new Date(), returns a new Date object. - When called as a function like
Date(), returns a string representation of the current date and time.
On the other hand, ObjectId and BinData are not classes but rather objects created by MongoDB. They have their own set of methods and properties, and they can be used directly without requiring the creation of instances through a constructor. Therefore, there is no need to use the new keyword when working with these objects.
I hope this clarifies your doubts.
Regards,
Kushagra
1 Like
