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:

(new Date).getTime()

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.

Read More:   Why is null in JavaScript bigger than -1, less than 1, but not equal (==) to 0? What is it exactly then?

As a matter of style, I prefer including all optional parens for consistency and clarity:

(new Date()).getTime()

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:

new Date().getTime();

one of good practice programmers follow to wrap object in parenthesis before calling function or property. so it will be:

(new Date()).getTime();

as discussed above object parenthesis are optional. So shorter cleaner code is:

(new Date).getTime();

You might want to have a look at this answer:
Can we omit parentheses when creating an object using the “new” operator?

Basicly new Date is equivilent to writing new Date() though you might prefer to use new Date() for consistency, since functions and constructors are so similar in JavaScript and the parentheses-less syntax is definitely illegal for function invocation.

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts