Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the '+new' mean in JavaScript?

Looking through the jQuery source in the function now() I see the following:

function now(){
    return +new Date;
}

I've never seen the plus operator prepended to the new operator like this. What does it do?

like image 486
Darrell Brogdon Avatar asked Dec 30 '09 23:12

Darrell Brogdon


4 Answers

function now(){
    return +new Date;
}

This function means the developer is clever.


function now(){
    return (new Date()).getTime();
}

This function means, get the current time in milliseconds since 1970. And the developer has some mercy for those who wish to understand WTF is going on.

like image 102
Bob Stein Avatar answered Oct 25 '22 07:10

Bob Stein


Nicolás and Brian are right, but if you're curious about how it works, +new Date(); is equivalent to (new Date()).valueOf();, because the unary + operator gets the value of its operand expression, and then converts it ToNumber.

You could add a valueOf method on any object and use the unary + operator to return a numeric representation of your object, e.g.:

var productX = {
  valueOf : function () {
    return 500; // some "meaningful" number
  }
};

var cost = +productX; // 500
like image 44
Christian C. Salvadó Avatar answered Oct 25 '22 09:10

Christian C. Salvadó


I think the unary plus operator applied to anything would cause it to be converted into a number.

like image 26
Nicolás Avatar answered Oct 25 '22 09:10

Nicolás


It converts the Date() into an integer, giving you the current number of milliseconds since January 1, 1970.

like image 42
Brian Campbell Avatar answered Oct 25 '22 09:10

Brian Campbell