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?

Answers:

Answer

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
Answer

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

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.