0

What is the difference between new Date and +new Date?

For example:

var date = new Date;
console.log(date);

var plusDate = +new Date;
console.log(plusDate);

Logs:

Sat May 10 2014 01:13:46 GMT+0300 (Jordan Standard Time)
1399673626539
Zirak
  • 38,920
  • 13
  • 81
  • 92
Mo Haidar
  • 3,748
  • 6
  • 37
  • 76
  • Looks like this question has been asked: http://stackoverflow.com/questions/221539/what-does-the-plus-sign-do-in-return-new-date – user3473534 May 09 '14 at 22:25

2 Answers2

3

The unary plus operator casts the Date object to a Number object (which is expressed in in milliseconds since 01 January, 1970 UTC).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • +1 - Does it implicitly call `.value`? Does date do the conversion internally or is it done somewhere else? – Travis J May 09 '14 at 22:24
  • @TravisJ—it's all [*in the spec*](http://ecma-international.org/ecma-262/5.1/#sec-11.4.6). – RobG May 09 '14 at 22:25
  • @RobG - Where in the spec does it mention calling .valueOf()? Because that is actually what seems to happen implicitly. http://jsfiddle.net/gcaFu/ – Travis J May 09 '14 at 22:27
  • @RobG - I see, "ToNumber(GetValue(expr))" calls GetValue, which "let getter be desc.[[Get]]" for the `expr` in which case `.valueOf()` is called. Date overrides object.prototype.valueOf and returns its time value. Thanks for the links :) – Travis J May 09 '14 at 22:36
-2

The first one creates a Date object, the second one adds the current date value in milliseconds to the original value of plusDate, which was 0.

tempoc
  • 377
  • 3
  • 7