DEV Community

loading...

Discussion on: Lesser-Known JavaScript Tricks

Collapse
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

Collapse
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
console.log(x.toString());

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: developer.mozilla.org/en-US/docs/W...

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😉

Collapse
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 :)

Forem Open with the Forem app