1

I am porting some javascript code (not my strongest language) and came across this:

Common._nowStartTime = +(new Date());

Common is a module and nowStartTime is a property of that module. I'm not sure what the right hand of the expression means? Why prefix with the unary + operator?

Garry Pettet
  • 8,096
  • 22
  • 65
  • 103

2 Answers2

1

According to MDN:

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number, if it isn't already.

It is commonly used as a shorthand for converting a value to a number. The conversion takes place by calling the value's .valueOf(). From MDN:

The shorthand notation is prefixing the variable with a plus sign: +"5"

Date implements its own Date.prototype.valueOf() documented here:

This method is functionally equivalent to the Date.prototype.getTime() method.

So the result is effectively a shorthand for this code:

Common._nowStartTime = new Date().getTime();
Klaycon
  • 10,599
  • 18
  • 35
-1

the expression +(new Date()) is the same as Number(new Date) so basically you are converting the date to a number timestamp

Common is an object so _nowStartTime is a property of Common