DEV Community

Discussion on: Top 5 JavaScript secrets

Collapse
 
bhagatparwinder profile image
Parwinder 👨🏻‍💻

You said that we can omit parentheses in a parameter-less class constructor. This has gotchas.

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

You addressed this in your blog post by saying

(new Date).getYear(); // parentheses needed in a different place

But why are those parentheses needed at a different place? Why doesn't it just work without parentheses? How will I remember that I need to use this confusing syntax?

 (new Date).getYear();

instead I could simply do

new Date().getYear();

This is what I am used to and it works.


Not giving you a hard time. There is a reason why you have to put the parentheses at a different place. It should be explained.

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 the 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();