user2039981
user2039981

Reputation:

JS - Which is correct, new Date or new Date()?

What's the correct syntax in JavaScript:

var x = new Date;

OR

var x = new Date();

?

Upvotes: 3

Views: 124

Answers (3)

tharindu_DG
tharindu_DG

Reputation: 9261

Both are correct. You could also use the parameterized constructors.

E.G:- var d = new Date(1993, 6, 28, 14, 39, 7);

    console.log(d.toString());     // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT)
    console.log(d.toDateString()); // prints Wed Jul 28 1993

Upvotes: -1

axelduch
axelduch

Reputation: 10849

Both are correct, just a matter of taste.

But usually it is preferred to use braces even though you don't pass any parameters, because these two snippets do not have the same evaluation:

Incorrect one

new Date.valueOf(); // to work it should be (new Date).valueOf()

Correct one

new Date().valueOf();

Upvotes: 3

Quentin
Quentin

Reputation: 943250

Both are correct. Parentheses are optional when the new operator is used and there are no arguments.

Upvotes: 3

Related Questions