3

What's the correct syntax in JavaScript:

var x = new Date;

OR

var x = new Date();

?

  • 2
    possible duplicate of [new MyObject(); vs new MyObject;](http://stackoverflow.com/questions/3034941/new-myobject-vs-new-myobject) – JJJ Dec 17 '14 at 09:58

3 Answers3

3

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

Quentin
  • 857,932
  • 118
  • 1,152
  • 1,264
3

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();
axelduch
  • 10,436
  • 2
  • 28
  • 49
-1

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
tharindu_DG
  • 8,182
  • 5
  • 51
  • 58
  • 1
    This post does **NOT** provide any answer to OP's problem! – undone Dec 17 '14 at 12:19
  • @undone: I have edited the answer. I just wanted to emphasize on the parameterized constructors of Date object. Thank you for pointing out the mistakes. – tharindu_DG Dec 20 '14 at 05:51