Search code examples
javascriptcompatibility

Difference between +new Date() and 1*new Date()


Google Analytics snippet uses 1*new Date() to get a current timestamp, which seems to be one character longer than +new Date() which I expected to be used for this purpose, especially taking into account how thoroughly minified GA snippet is.

I had a look at ES5 spec and it looks like it should be the same: unary plus applies ToNumber(GetValue(expr)) and returns it, multiplication applies ToNumber(GetValue(expr)) to both sides and multiplies them.

Is there a JavaScript environment (maybe some old browser?) which produces different results for +new Date() and 1*new Date()?


Solution

  • There is no semantic difference; both will return the same value in all JavaScript implementations.

    As already identified, this is because the conversion happens with [ToNumber], which applies equally to the unary + and the infix * operands.

    This assumes that the expression shown is complete as it's somewhat easy to 'accidentally' turn the unary + into an infix without a syntax error; and an infix + could undesirably result in string concatenation. These days I just use Date.now() (ES5, shimmed elsewhere) although I used to use (+new Date).