Skip to content Skip to sidebar Skip to footer

Multiplication With Date Object - Javascript

I came across this piece of code var timeStamp = 1 * new Date(); and to my surprise it returned value in milliseconds since 1970/01/01. This is equivalent to using .getTime() metho

Solution 1:

What's happening under the hood?

The short version:

Because it's being used in a math operation, the date is converted to a number, and when you convert dates to numbers, the number you get is the milliseconds-since-the-Epoch (e.g., getTime()).

The long version:

  1. The multiplication operator calls the abstract operation ToNumber on its operands.

  2. For objects like Dates, that calls the abstract operation ToPrimitive on the object, with the "preferred type" being "number".

  3. For most types of objects (including Dates), ToPrimitive calls the abstract operation [[DefaultValue]], passing along the preferred type as the "hint".

  4. [[DefaultValue]] with hint = "number" calls valueOf on the object. (valueOf is a real method, unlike the abstract operations above.)

  5. For Date objects, valueOf returns the "time value," the value you get from getTime.


Side note: There's no reason I can think of to use var timeStamp = 1 * new Date() rather than, say, var timeStamp = +new Date(), which has the same effect. Or of course, on any modern engine (and the shim is trivial), var timeStamp = Date.now() (more on Date.now).

Solution 2:

Numeric conversion

It is because of numeric conversion in javascript which is almost same like toString but internally it is called much more often.

Numeric conversion is performed in two main cases:

  • In functions which needs a number: for example Math.sin(obj), isNaN(obj), including arithmetic operators: +obj.
  • In comparisons, like obj == 'John'. The exceptions are the string equality ===, because it doesn’t do any type conversion, and also non-strict equality when both arguments are objects, not primitives: obj1 == obj2. It is true only if both arguments reference the same object.

The explicit conversion can also be done with Number(obj).

The algorithm of numeric conversion:

  • If valueOf method exists and returns a primitive, then return it.

  • Otherwise, if toString method exists and returns a primitive, then return it.

  • Otherwise, throw an exception.

Among built-in objects, Date supports both numeric and string conversion:

alert( newDate() ) // The date in human-readable formalert( 1*newDate() ) // Microseconds from 1 Jan 1970

Further reading

Post a Comment for "Multiplication With Date Object - Javascript"