Multiplication with a date object - javascript

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

What happens under the hood? Is the concept of type conversion used, which basically converts the value new Date()to milliseconds?

+4
source share
2 answers

What happens under the hood?

Short version:

Since it is used in a mathematical operation, the date is converted to a number, and when you convert dates to numbers, the number you get is milliseconds-s-epoch (for example, getTime()).

Long version:


. , var timeStamp = 1 * new Date(), , , var timeStamp = +new Date(), . , , ( ), var timeStamp = Date.now() ( Date.now).

+7

- javascript, , toString, .

:

  • , : , Math.sin(obj), isNaN (obj), : + obj.
  • , obj == 'John'. ===, , , , : obj1 == obj2. , .

Number (obj).

:

  • valueOf , .

  • , toString , .

  • .

Date , :

alert( new Date() ) // The date in human-readable form
alert( 1*new Date() ) // Microseconds from 1 Jan 1970

+1

Source: https://habr.com/ru/post/1544307/


All Articles