I have seen objects being created this way:
const obj = new Foo;
But I thought that the parentheses are not optional when creating an object:
const obj = new Foo();
Is the former way of creating objects valid and defined in the ECMAScript standard? Are there any differences between the former way of creating objects and the later? Is one preferred over the other?
Quoting David Flanagan1:
As a special case, for the
new
operator only, JavaScript simplifies the grammar by allowing the parenthesis to be omitted if there are no arguments in the function call. Here are some examples using thenew
operator:o = new Object; // Optional parenthesis omitted here d = new Date(); ...
Personally, I always use the parenthesis, even when the constructor takes no arguments.
In addition, JSLint may hurt your feelings if you omit the parenthesis. It reports Missing '()' invoking a constructor
, and there doesn't seem to be an option for the tool to tolerate parenthesis omission.
1 David Flanagan: JavaScript the Definitive Guide: 4th Edition (page 75)