There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

Literal way:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.

Answer from Rémy DAVID on Stack Overflow
Top answer
1 of 13
252

There is no difference for a simple object without methods as in your example. However, there is a big difference when you start adding methods to your object.

Literal way:

function Obj( prop ) { 
    return { 
        p : prop, 
        sayHello : function(){ alert(this.p); }, 
    }; 
} 

Prototype way:

function Obj( prop ) { 
    this.p = prop; 
} 
Obj.prototype.sayHello = function(){alert(this.p);}; 

Both ways allow creation of instances of Obj like this:

var foo = new Obj( "hello" ); 

However, with the literal way, you carry a copy of the sayHello method within each instance of your objects. Whereas, with the prototype way, the method is defined in the object prototype and shared between all object instances. If you have a lot of objects or a lot of methods, the literal way can lead to quite big memory waste.

2 of 13
135

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

These

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/ 
-or-

person = {
    property1 : "Hello"
};

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

// Don't do this
Object = 23;

In that highly-unusual case, new Object will fail but {} will work.

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

🌐
Medium
medium.com › @mazahar_shaikh › javascript-object-literal-v-s-new-object-difference-performance-ac8360dd6caf
JavaScript — Object literal {} V/S new Object() difference & Performance | by Mazahar Shaikh | Medium
September 17, 2019 - {} is literal and literals are evaluated faster in JavaScript, but new Object() is a constructor call to function Object() which is having its own definition that takes comparatively more time to evaluate.
Discussions

What's the difference between an object literal and JSON? When do you use which?
What's the difference? And how do you choose when to use which? :D ... Happy to hear you're loving the course, best of lucks in your journey! An Object literal is when you declare an Object in JavaScript code which is a variable that stores data in key-value pairs, while JSON stands for JavaScript ... More on teamtreehouse.com
🌐 teamtreehouse.com
1
July 23, 2020
Object and Object Literals in javascript - Stack Overflow
Will anyone please explain the difference between object and object literals in JavaScript? So far I learned by searching google is given bellow: 1) Object is a collection of name-value pairs li... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Should I be using object literals or constructor functions? - Stack Overflow
The latter may be usefull in some cases. Most of the times an Object literal is sufficient and a nice and clean way to create a JS-object. ... What's the difference between a function and a method? I come from a c# background so to me a function is standalone and a method is just a function that is part of a class. 2011-02-01T18:49:58.277Z+00:00 ... There's not that much difference, see for example web-source.net/javascript... More on stackoverflow.com
🌐 stackoverflow.com
What are the pros and cons of using object literal notation vs class notation?
They aren't the same, for one. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes More on reddit.com
🌐 r/javascript
6
0
January 11, 2016
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Working_with_objects
Working with objects - JavaScript - MDN Web Docs - Mozilla
February 21, 2026 - You can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object by invoking that function with the new operator. Object initializers are also called object literals.
🌐
Kevin Chisholm
blog.kevinchisholm.com › javascript › difference-between-object-literal-and-instance-object
What is the difference between an Object Literal and an Instance Object in JavaScript ? | Kevin Chisholm - Blog
February 10, 2021 - We have created an instance of Foo() by saying “var bar = new Foo()”. So, now we have a variable named “bar” that is an exact copy of Foo(). What makes “bar” differ from our JavaScript Object Literal that we defined in Example # 1, is that when our instance object (“bar”) is created, any execution code in the constructor (i.e.
🌐
Medium
medium.com › @mandeepkaur1 › object-literal-vs-constructor-in-javascript-df143296b816
Object Literal vs. Constructor in Javascript | by Mandeep Kaur | Medium
November 5, 2018 - Let’s see how to define them: ... let us have multiple instances of that object. Object literals are basically singletons with variables that are all public....
Find elsewhere
🌐
Internal Pointers
internalpointers.com › post › object-literals-vs-constructors-javascript
Object literals vs constructors in JavaScript - Internal Pointers
With the constructor function notation you create an object that can be instantiated into multiple instances (with the new keyword), while the literal notation delivers a single object, like a singleton.
Top answer
1 of 12
134

If you don't have behaviour associated with an object (i.e. if the object is just a container for data/state), I would use an object literal.

var data = {
    foo: 42,
    bar: 43
};

Apply the KISS principle. If you don't need anything beyond a simple container of data, go with a simple literal.

If you want to add behaviour to your object, you can go with a constructor and add methods to the object during construction or give your class a prototype.

function MyData(foo, bar) {
    this.foo = foo;
    this.bar = bar;

    this.verify = function () {
        return this.foo === this.bar;
    };
}

// or:
MyData.prototype.verify = function () {
    return this.foo === this.bar;
};

A class like this also acts like a schema for your data object: You now have some sort of contract (through the constructor) what properties the object initializes/contains. A free literal is just an amorphous blob of data.

You might as well have an external verify function that acts on a plain old data object:

var data = {
    foo: 42,
    bar: 43
};

function verify(data) {
    return data.foo === data.bar;
}

However, this is not favorable with regards to encapsulation: Ideally, all the data + behaviour associated with an entity should live together.

2 of 12
101

It essentially boils down to if you need multiple instances of your object or not; object defined with a constructor lets you have multiple instances of that object. Object literals are basically singletons with variables/methods that are all public.

// define the objects:
var objLit = {
  x: 0,
  y: 0,
  z: 0,
  add: function () {
    return this.x + this.y + this.z;
  }
};

var ObjCon = function(_x, _y, _z) {
  var x = _x; // private
  var y = _y; // private
  this.z = _z; // public
  this.add = function () {
    return x + y + this.z; // note x, y doesn't need this.
  };
};

// use the objects:
objLit.x = 3; 
objLit.y = 2; 
objLit.z = 1; 
console.log(objLit.add());    

var objConIntance = new ObjCon(5,4,3); // instantiate an objCon
console.log(objConIntance.add());
console.log((new ObjCon(7,8,9)).add()); // another instance of objCon
console.log(objConIntance.add()); // same result, not affected by previous line
🌐
YouTube
youtube.com › watch
Object literal vs object constructor - YouTube
Link for all dot net and sql server video tutorial playlistshttp://www.youtube.com/user/kudvenkat/playlistsLink for slides, code samples and text version of ...
Published   February 1, 2015
🌐
Medium
medium.com › @jetti.dinesh › object-creation-literal-vs-constructor-vs-class-importance-of-static-in-js-a4c9a1f62523
Object Creation — Literal vs Constructor vs Class & Importance of Static in JS | by DINESH REDDY JETTI | Medium
November 18, 2023 - No Encapsulation: Object literals do not provide encapsulation, which means there’s no clear distinction between public and private properties or methods. This can lead to potential issues with data integrity and security. Difficulty in Adding Methods: While you can add methods to an object literal, if you have many methods or more complex behavior, it may be more organized to use a constructor function or class. With object literals, functions must be defined within the object, which can lead to less readable code. In JavaScript, a “blueprint” typically refers to a constructor function or a class that serves as a template for creating objects with similar properties and methods.
🌐
TutorialsPoint
tutorialspoint.com › what-is-the-main-difference-between-objects-created-using-object-literal-and-constructor-function
What is the main difference between objects created using object literal and constructor function?
July 30, 2019 - Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.
🌐
Medium
medium.com › @dinusha-s › javascript-object-literal-d69a536be85
JavaScript — Object Literal
July 18, 2023 - When you declare an object using the curly brace like this called the object literal Syntax. The big difference between objects and arrays is that in objects the order of these values does not matter at all when we want to retrieve them.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Operators › Object_initializer
Object initializer - JavaScript - MDN Web Docs - Mozilla
The only exception is that the object literal syntax prohibits duplicate __proto__ keys, which does not apply to JSON.parse(). The latter treats __proto__ like a normal property and takes the last occurrence as the property's value. The only time when the object value they represent (a.k.a. their semantic) differ is also when the source contains the __proto__ key — for object literals, it sets the object's prototype; for JSON, it's a normal property.
🌐
Codecademy
codecademy.com › forum_questions › 55fb387e86f552e9e20000d6
object literal vs. object constructor | Codecademy
Just curious why someone would choose between these two. Thanks ... One advantage is less typing, and for us that’s a plus. It also lends itself to directly defined properties which we can just open up the block and insert to our content. var obj = { type: 'object', keys: 'type' } console.log(obj.type); // object console.log(obj.keys); // type
🌐
Quora
quora.com › What-is-the-difference-between-these-object-literals-in-JavaScript
What is the difference between these object literals in JavaScript? - Quora
Answer (1 of 10): In pure Javascript there is no difference. Both objects are the same. But some Javascript preprocessors, like Google Closure Compiler, can do obfuscation with the second variant.
🌐
Reddit
reddit.com › r/javascript › what are the pros and cons of using object literal notation vs class notation?
r/javascript on Reddit: What are the pros and cons of using object literal notation vs class notation?
January 11, 2016 -

What I mean by object notation is defining a class as an object, like this:

var food = {
var taste : "";
create: function(initTaste){
var temp = Object.create(this);
this.taste = initTaste;
return temp;
}

var sandwich = food.create("salty"); var candy = food.create("sweet");

While class notation is typical "class food" format.

Which one would be advisable to use and why? Also, if I were to convert the above example into "class" what would it look like?

Top answer
1 of 3
6

In JavaScript, the keys in object literal notation are treated as strings whether or not they are in quotes. Thus, with this:

var car = { manyCars : {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

If you then do this:

for (var k in car) { console.log("key: " + k + " (type: " + typeof(k) + ")"); }

the output will be:

key: 7 (type: string)
key: manyCars (type: string)

Note that the (apparently) numeric key 7 is also a string. You can even use JavaScript keywords as keys in an object literal.

Note that when accessing a value by key, the rules are more stringent. For instance, you must use subscript notation and quotes when a key is a reserved word. Also, a bare key in an object literal must (if it isn't a numeric literal) be a valid JavaScript identifier name, so it cannot contain spaces, commas, or JavaScript operators (+, =, etc.).

2 of 3
2

In JavaScript objects literals are made up of key-value pairs. Keys in JavaScript are always strings while values may be of any data type.

JavaScript provides syntactic sugar for defining keys. For example unlike string literals you don't need to quote keys. Hence the following two examples are equivalent:

{ x: 0 }   // example 1
{ "x": 0 } // example 2

However this syntactic sugar only works for identifiers that don't have any whitespace (i.e. spaces, tabs, newlines, etc.) in between them. For example, the following is invalid in JavaScript:

{ a property: 0 } // whitespace not allowed in identifiers

However you can workaround this limitations by quoting the identifier:

{ "a property": 0 } // valid

You may also use boolean (true or false), number literals and undefined and null as keys. However remember that they are coerced to strings. Hence you can do:

var o = {
    undefined: 1,
    null: 2,
    true: 3,
    false: 4,
    0: 5
};

Then you can access them as:

alert(o.undefined); // 1
alert(o.null);      // 2
alert(o.true);      // 3
alert(o.false);     // 4
alert(o[0]);        // 5

The last statement is important. Number literals by themselves do not classify as valid identifiers. Hence you need to use the array bracket notation ([]) instead of the dot notation (.) to access it.

Since all keys in JavaScript are strings you could even do:

alert(o["undefined"]); // 1
alert(o["null"]);      // 2
alert(o["true"]);      // 3
alert(o["false"]);     // 4
alert(o["0"]);         // 5

However you can't use objects, arrays or functions as keys. For example the following is invalid:

{ {1: 2}: 3 }            // objects can't be used as keys
{ [1]: 2 }               // arrays can't be used as keys
{ function () {}: true } // functions can't be used as keys

That's all you need to know about object literals.