5

I am trying to understand the use of extra parentheses around the Date constructor in the following return statement:

if (!Date.now) {
  Date.now = function now() {
    return +(new Date); // <-- ???
  };
}

Source

Are there any edge-cases in which these parentheses cannot be omitted? Thanks!

  • 2
    I think they're just for clarity. Surely you agree that `+new {whatever}` looks oddly like we're doing something directly to `new`. – kojiro Jan 04 '13 at 19:17
  • 1
    It is just optional in this present scenario... But it makes it easier to understand and to mitigate the confusion.. – Sushanth -- Jan 04 '13 at 19:17
  • 1
    There's another post on stackoverflow that addresses this. It looks like it is trying to convert the new date object to a number. In either case, I think the parentheses are optional. http://stackoverflow.com/questions/221539/what-does-the-plus-sign-do-in-return-new-date – AceCorban Jan 04 '13 at 19:18
  • 1
    It's the grouping operator: http://es5.github.com/#x11.1.6. Sometimes it is necessary to use it and sometimes it just makes the code easier to read/understand. You could also write `return +new Date;`, but it might not be immediately clear in which order this is executed. – Felix Kling Jan 04 '13 at 19:19
  • Sometimes parens are for the programmer, not the compiler/interpreter. – Alex Wayne Jan 04 '13 at 19:19

1 Answers1

0

Parentheses are not necessary.

return +new Date; 

works as well. Parentheses are needed to help the understanding of an expression but they can also change the default order of precedence of an evaluation. This order is defined in the lexical grammar section of the ECMAScript.

http://www.ecma-international.org/ecma-262/5.1/#sec-A.1

Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240