Why would you invoke new Date without parentheses?

constructor, datetime, javascript

Solution

You can invoke constructors in JS w/o the parenthesis if no arguments are to be passed, the effect is the same.

`new Date()` vs `new Date` the same.

However, it makes a difference when you want to call a method on the resulting object:

`new Date().getTime()` works but `new Date.getTime()` would not because in the latter case the interpreter assumes `getTime` is a method of the Date type which isn't the case, `getTime` is an instance method. To overcome this you can wrap parenthesis around the constructor call to tell the interpreter that it is an expression:

`(new Date).getTime()`

This way first the expression is evaluated and `getTime` is called on the result which is an instance of Date.

Problem

I have just seen this snippet while accidentally opening dev tools in Gmail: ``` var GM_TIMING_END_CHUNK1=(new Date).getTime(); ``` I would usually expect something like this, as it's rather uncommon to invoke a constructor without parentheses (at least I have never seen it until now): ``` var GM_TIMING_END_CHUNK1=new Date().getTime(); ``` or ``` var GM_TIMING_END_CHUNK1=Date.now(); //newer browsers ``` Is there any advantage in doing so, any difference in behavior? It's the exact same amount of characters needed, so brevity won't be a reason.

Original source

Related problems