views:

580

answers:

5

I've seen this in a few places

function(){ return +new Date; }

And I can see that it is returning a timestamp rather than a date object, but I can't find any documentation on what the plus sign is doing.

Can anyone explain?

+8  A: 

JavaScript is loosely typed, so it performs type coercion/conversion in certain circumstances:

http://blog.jeremymartin.name/2008/03/understanding-loose-typing-in.html
http://www.jibbering.com/faq/faq_notes/type_convert.html

Other examples:

>>> +new Date()
1224589625406
>>> +"3"
3
>>> +true
1
>>> 3 == "3"
true
insin
+1  A: 

It does exactly the same thing as:

function(){ return 0+new Date; }

that has the same result as:

function(){ return new Date().getTime(); }
Sergey Ilinsky
Nope on 0+new Date. That first converts the date to a string and then prepends a "0", (eg: "0Tue Oct 21 2008 20:38:05 GMT-0400");
Chris Noe
1 * new Date will, but 1 + new Date --> String
Kent Fredric
+21  A: 

that's the + unary operator, it's equivalent to:

function(){ return Number(new Date); }

see: http://xkr.us/articles/javascript/unary-add/

kentaromiura
Good stuff - "Values of type Date will be converted to their corresponding numerical value (via valueOf()), which is the number of milliseconds since the UNIX epoch."
Kon
A: 

The unary plus converts the Date object to a String, and then converts it to a number, with the operator then applied to the number. A unary plus does nothing to the number, giving the result.

janm
+3  A: 

Here is the specification regading the "unary add" operator. Hope it helps...

Pablo Cabrera