Why Date need 'new' keyword to create Date object and ObjectId do not need any?

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 Date constructor 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

I think adding or not adding ‘new’ keyword does not make any difference. I tried with different data types. It creates more confusion. Also, IMO mongodb should have it’s own rules and should not mix itself with javascript.