5

Possible Duplicate:
new MyObject(); vs new MyObject;

In some articles I seen following statement to create new object in JavaScript:

var myObject = new Object;

and at some sites:

var myObject = new Object();

In there is any difference between two statements or one is just shorthand?

Community
  • 1
  • 1
daljit
  • 1,256
  • 1
  • 11
  • 30

3 Answers3

8

There's no difference. Parentheses are optional when using a function as a constructor (i.e. with the new operator) and no parameters. When not using the new operator, parentheses are always required when calling a function.

As noted in another answer, it's generally preferable to use an object literal instead. It has the following advantages over using the Object constructor:

  • Allows concise initialization of properties (e.g. var foo = { bar: "cheese" };)
  • Shorter
  • Possibly faster
  • Unaffected in the (unlikely) event of the Object function being overwritten.
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • +1 Very good answer, didn't know about the last thing (Unaffected in the (unlikely) event of the Object function being overwritten.). – helpermethod Feb 20 '12 at 12:08
1

Easy answer - don't use that syntax. The preferred way for creating objects in JavaScript is to use the following syntax:

var myObject = {}; // creates an empty object
robyaw
  • 2,274
  • 2
  • 22
  • 29
1

There is no difference. It just happens that in this special case, you can omit the ().

So new Object()

and

new Object

are equivalent.

BTW, there is also no difference in using new Object() over {}. Use whatever you prefer.

helpermethod
  • 59,493
  • 71
  • 188
  • 276