Blake
Blake

Reputation: 7547

why +new Date() return the same as new Date().getTime()?

I was reading some source code, and find this. why +new Date() return the same as new Date().getTime()? What's the mechanism behind it?

var date = new Date()
+data == date.getTime() // true

Upvotes: 1

Views: 110

Answers (2)

Knu
Knu

Reputation: 15136

That's because the unary + operator—when used on types other than strings—will internally call valueOf. In the case of a date, it is functionally equivalent to Date.prototype.getTime, as both perform the same abstract operation.

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816374

The unary + operator converts the operand to a number. In that process, date.valueOf will be called, which performs the same computation as date.getTime.

Upvotes: 3

Related Questions