views:

91

answers:

4

What are the differences between these two codes in JavaScript?

var obj = new Object();
obj.X = 10;
obj.Y = 20;

And,

var obj = {X:10, Y:20};
+4  A: 

The second is a shortcut for the first. Functionally they are the same.

Kai
Not necessarily a shortcut, but different syntax. The second one is called JavaScript Object Notation, or JSON.
opello
No, the second isn't JSON. JSON would be {"X":10, "Y":20}. The quoting is important.
Anthony Mills
Ah sorry, you are indeed correct. Hm, what would it be called then? Is it just 'shortcut object syntax?'
opello
@opello It's called "object literal" syntax
Greg
A: 

Nothing really. Well, that's not quite true, but the differences are far too minor to mention.

Anthony Mills
+4  A: 

Nothing at all. Just syntax.

You could also use:

var obj = new Object();
obj["X"] = 10;
obj["Y"] = 20;
Seth Illgard
+1  A: 

Object literal format {} was introduced with JavaScript 1.2, along with Array literal format [].

So the more readable variant {X:10, Y:20} won't work in Netscape 3! (Oh no!)

bobince