user366312
user366312

Reputation: 16908

JavaScript objects

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};

Upvotes: -1

Views: 311

Answers (4)

bobince
bobince

Reputation: 536379

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!)

Upvotes: 1

Daniel Rodriguez
Daniel Rodriguez

Reputation: 1483

Nothing at all. Just syntax.

You could also use:

var obj = new Object();
obj["X"] = 10;
obj["Y"] = 20;

Upvotes: 5

Anthony Mills
Anthony Mills

Reputation: 8784

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

Upvotes: 0

Kai
Kai

Reputation: 9552

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

Upvotes: 4

Related Questions