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?
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?
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
It does exactly the same thing as:
function(){ return 0+new Date; }
that has the same result as:
function(){ return new Date().getTime(); }
that's the + unary operator, it's equivalent to:
function(){ return Number(new Date); }
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.
Here is the specification regading the "unary add" operator. Hope it helps...