DEV Community

Discussion on: Lesser-Known JavaScript Tricks

melvincarvalho profile image
Melvin Carvalho

Great post. Slight nit:

The only time you would need those brackets is if a constructor expects arguments.

new Date().toString() // works
new Date.toString() // fails

bhagatparwinder profile image
Parwinder 👨🏻‍💻 Author

I am so glad you brought this up. I would love to explain this! There is a reason why this works:

const x = new Date; // What I taught in this blog post

And this does not

new Date.toString();

It's because new Date.toString() is not equal to new Date().toString(). *There is an extremely subtle difference. They have different precedence. *

Check out:

new Date.toString() throws an error because . has higher precedence than new Date so the expression becomes (or it is resolved as) (new (Date.toString))(). They might look same but they are evaluated differently!

In short, if you would like to invoke the constructor and chain it with a method in the object, the correct syntax is:

(new Date).toString();

Give it a try😉

melvincarvalho profile image
Melvin Carvalho

That's pretty amazing thanks!

So when chaining you dont save typing the parentheses, they can just go in two different places :)