Reputation: 14318
In order to take the Timestamps in javascript yuo can write this kind of code:
// Usual Way
var d = new Date();
timestamp = d.getTime();
But I found that is it also possible to get the same result in this way:
// The shortest Way
timestamp = +new Date();
Can someone help me to understand how the Shortest Way works?
Upvotes: 3
Views: 296
Reputation: 237827
That is the unary plus operator. It attempts to convert the argument that follows into a number if it isn't already a number. The Date
object implements a method that allows it to be converted to a number, which is the timestamp identical to the getTime()
method.
A more legible and obvious way of getting a timestamp without using an extra variable is to use parentheses:
var timestamp = (new Date()).getTime();
Upvotes: 5
Reputation: 85476
JavaScript is a dynamic typed language, and it will try conversions appropriate to the context.
When adding a unary plus in front of the Date Object it will be converted to a number.
Upvotes: 0