What’s the unary + operator?

During development recently I’ve been seeing statements like this in Javascript:

var currentTime = +new Date();

What’s that plus (‘+’) symbol doing there, before the ‘new’ operator? Strangely, it wasn’t trivial to find out on google, as I only knew the symbol not the name, but I found it on this very useful and concise blog post. It is the unary + or unary add operator.

It does what I suspected. It looks like a mathematical plus which I’ve used to add two numbers together, or when creating strings with variables. This is a very concise use of it. When used on a variable, like new Date(), it converts that variable into a Number. It’s worth noting how it does this. First it will attempt to call .valueOf() on that variable, and convert to a number. If that fails, it will call .toString(), and convert that output into a Number. If all else fails, it will become NaN.

So in this example, the code above is achieves the same effect of:

var currentTime = (new Date()).getTime();

But looks nicer. Albeit a little unobvious.

Source: xkr.us