This is an interesting use of the unary +
operator. Basically, you can break down this expression into three separate parts, splitting at the binary +
operator:
"sth"
, then +
, then +new Date
.
The first operand of the binary +
is just a generic string literal. The second operand uses the unary +
operator, which, as the linked standard states, converts its operand to a Number
.
Because the new
operator has the highest precedence, it "binds tighter" than the unary +
, which means new Date
will be evaluated first. So the operand of the unary +
is, in turn, the result of the expression new Date
. Of course, new Date
simply creates a blank Date
object. As per § 15.9.3.3 new Date():
The [[PrimitiveValue]] internal property of the newly constructed
object is set to the time value (UTC) identifying the current time.
In other words, a new Date
will just be a Date
object representing the current time. And, in turn, +new Date
will convert a blank Date
object to a number.
The Short Answer
The specification is long and hard to follow. In short, +new Date
returns the UNIX timestamp associated with the current time.
The Long Answer: Following the Spec
The long answer, following the specification, is that the unary +
calls ToNumber(GetValue(expr))
where expr
is the evaluated operand. GetValue(dateObj)
will simply return dateObj
, so the expression then becomes ToNumber(dateObj)
.
The result of ToNumber
depends on what the type of the argument is. In the case of an object, it returns ToNumber(ToPrimitive(input argument, hint Number))
.
ToPrimitive
will, in turn, call the valueOf
property of the Date
object. That returns a Number
, which is the time value associated with the Date
object: finally, what we were looking for! Then it goes back up the chain: ToNumber(num)
simply returns num
.
Of course, from there, the string "sth"
and the result of +new Date
are concatenated (you can find that in the spec if you so wish), which gives you the result you were looking for.