Why would you invoke new Date without parentheses? [duplicate]
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();
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.
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:
This way first the expression is evaluated and
getTime is called on the result which is an instance of Date.
In addition to the existing comments about optional parentheses — i.e.
new Date() <==> new Date — note also that
Date.now is a static method. That is, no
Date object is ever instantiated. The method is a property of the
Date constructor itself. In this way, it is different than the other two examples.
As a matter of style, I prefer including all optional parens for consistency and clarity:
When a function is used as an object constructor and no arguments are being passed, the parentheses are optional.
d = new Date; means the same thing as
d = new Date();.
There is no difference in both statements, parenthesis are optional, So usually programmers drop it.
In your second example:
one of good practice programmers follow to wrap object in parenthesis before calling function or property. so it will be:
as discussed above object parenthesis are optional. So shorter cleaner code is:
You might want to have a look at this answer:
Can we omit parentheses when creating an object using the “new” operator?
new Date is equivilent to writing
new Date() though you might prefer to use