Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+new Date() - Is this good practice?

Tags:

javascript

So we had the Discussion today in our company about +new Date() being good practice or not. Some prefer this way over new Date().getTime().

In my opinion, this is pretty convenient but on the other side one would say it's harder to read.

Are there any pros or cons besides the obvious "It's harder to understand for people not familiar with the unary operator"?

like image 422
Julian Hollmann Avatar asked Jan 10 '13 10:01

Julian Hollmann


People also ask

Does new date () Return current date?

Use new Date() to generate a new Date object containing the current date and time. This will give you today's date in the format of mm/dd/yyyy.

Is new date () async?

log("Now: " + (new Date()). toString()); It's a bit confusing because this piece of code look like a synchronous code: no callback appears in the code. But in fact, it is asynchronous.

What is the difference between new date () and date ()?

Date() returns an implementation dependent string representing the current date and time. new Date() returns a Date object that represents the current date and time. ;-) Yeah, I know.

What does new date do in JavaScript?

The Date object is created by using new keyword, i.e. new Date(). The Date object can be used date and time in terms of millisecond precision within 100 million days before or after 1/1/1970.


1 Answers

The getTime method appears to be a huge amount faster:

enter image description here

Why is this the case?

Here's what happens when you call the getTime method on a Date instance:

  1. Return the value of the [[PrimitiveValue]] internal property of this Date object.

Here's what happens when you apply the unary plus operator to a Date instance:

  1. Get the value of the Date instance in question
  2. Convert it to a Number
    1. Convert it to a primitive
      1. Call the internal [[DefaultValue]] method
like image 150
James Allardice Avatar answered Sep 19 '22 17:09

James Allardice