Prasad K - Google
Prasad K - Google

Reputation: 2584

Difference between new Date().valueOf() and new Date() * 1 in javascript

What is the difference between

new Date().valueOf() 

and

new Date() * 1

Both give the same value, is there any performance difference? (Just out of curiosity)

Upvotes: 2

Views: 1112

Answers (2)

Hugo S. Mendes
Hugo S. Mendes

Reputation: 1086

as you can see here:

http://jsperf.com/new-date-test-1

the (new Date()).valueOf is faster than new Date() * 1

looks like the new Date() * 1 needs to perform an operation to, only after that, call the .valueOf method.

Hope it helps.

Upvotes: 3

Pointy
Pointy

Reputation: 413737

Using an object in a multiplication expression implicitly involves a call to .valueOf() anyway, so there's really no difference at all. That is, the way that the expression

new Date() * 1

is interpreted involves an attempt to get the operand on the left side of the * operator to be a number. That's what the .valueOf() method is supposed to do. For Date instances, that returns the millisecond timestamp value.

Note that

Date.now()

is also equivalent. (Not new Date().now(); the "now" function is a property of the Date constructor.)

Upvotes: 6

Related Questions