Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "{}" and "new Object()" [duplicate]

Tags:

javascript

Possible Duplicate:
creating objects - new object or object literal notation?

What exactly is the difference between the following:

var myData = new Object();
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";

and

var myData = {};
myData["name"] = "ATOzTOA";
myData["site"] = "atoztoa";

Update

What I got is this...

var myData = {
    "name" : "ATOzTOA",
    "site" : "atoztoa",
};

is a shortcut to

var myData = new Object({
    "name" : "ATOzTOA",
    "site" : "atoztoa",
});

Am I right?

like image 214
ATOzTOA Avatar asked Dec 27 '12 08:12

ATOzTOA


People also ask

What is the difference between {} and []?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What is the use of {} in JavaScript?

{} declares an object, with no members. Like an empty data container. [] would declare an empty array. Fun fact: Even arrays are objects in JavaScript.

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

What is the difference between object create and new object?

The major difference is that Object. Create returns the new object while the constructor function return the constructor of the object or the object. This is due to the important difference that new actually runs constructor code, whereas Object. create will not execute the constructor code.


2 Answers

There is no difference (technically). {} is just a shortcut for new Object().

However, if you assign an object literal, you may directly form a new object with multiple properties.

var myData = {
    name:   'ATOzTOA',
    size:   'atoztoa'
};

..which might feel more convenient. Also, it reduces the access on the object and is ultimately faster. But that is about microoptimizations. More important is that its a lot less to type.

like image 100
jAndy Avatar answered Sep 21 '22 12:09

jAndy


Nothing. {} just a short hand for new Object()

Its same logic as your full name is 'Mark Zuckerberg' and people call you ' Hi Mark'

like image 41
Akhil Sekharan Avatar answered Sep 17 '22 12:09

Akhil Sekharan