[javascript] Create an empty object in JavaScript with {} or new Object()?

There are two different ways to create an empty object in JavaScript:

var objectA = {}
var objectB = new Object()

Is there any difference in how the script engine handles them? Is there any reason to use one over the other?

Similarly it is also possible to create an empty array using different syntax:

var arrayA = []
var arrayB = new Array()

The answer is


Array instantiation performance

If you wish to create an array with no length:

var arr = []; is faster than var arr = new Array();

If you wish to create an empty array with a certain length:

var arr = new Array(x); is faster than var arr = []; arr[x-1] = undefined;

For benchmarks click the following: https://jsfiddle.net/basickarl/ktbbry5b/

I do not however know the memory footprint of both, I can imagine that new Array() takes up more space.


OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

Surprisingly, it's creating a Number!

var a = new Object([1,2,3]); //[1, 2, 3]

And this is creating a Array!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!


Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.


I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.


var objectA = {}

is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.


Var Obj = {};

This is the most used and simplest method.

Using

var Obj = new Obj() 

is not preferred.

There is no need to use new Object().

For simplicity, readability and execution speed, use the first one (the object literal method).


OK, there are just 2 different ways to do the same thing! One called object literal and the other one is a function constructor!

But read on, there are couple of things I'd like to share:

Using {} makes your code more readable, while creating instances of Object or other built-in functions not recommended...

Also, Object function gets parameters as it's a function, like Object(params)... but {} is pure way to start an object in JavaScript...

Using object literal makes your code looks much cleaner and easier to read for other developers and it's inline with best practices in JavaScript...

While Object in Javascript can be almost anything, {} only points to javascript objects, for the test how it works, do below in your javascript code or console:

var n = new Object(1); //Number {[[PrimitiveValue]]: 1}

Surprisingly, it's creating a Number!

var a = new Object([1,2,3]); //[1, 2, 3]

And this is creating a Array!

var s = new Object('alireza'); //String {0: "a", 1: "l", 2: "i", 3: "r", 4: "e", 5: "z", 6: "a", length: 7, [[PrimitiveValue]]: "alireza"}

and this weird result for String!

So if you are creating an object, it's recommended to use object literal, to have a standard code and avoid any code accident like above, also performance wise using {} is better in my experience!


The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...


These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.


var objectA = {}

is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.


I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.


These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.


The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...


Yes, There is a difference, they're not the same. It's true that you'll get the same results but the engine works in a different way for both of them. One of them is an object literal, and the other one is a constructor, two different ways of creating an object in javascript.

var objectA = {} //This is an object literal

var objectB = new Object() //This is the object constructor

In JS everything is an object, but you should be aware about the following thing with new Object(): It can receive a parameter, and depending on that parameter, it will create a string, a number, or just an empty object.

For example: new Object(1), will return a Number. new Object("hello") will return a string, it means that the object constructor can delegate -depending on the parameter- the object creation to other constructors like string, number, etc... It's highly important to keep this in mind when you're managing dynamic data to create objects..

Many authors recommend not to use the object constructor when you can use a certain literal notation instead, where you will be sure that what you're creating is what you're expecting to have in your code.

I suggest you to do a further reading on the differences between literal notation and constructors on javascript to find more details.


var objectA = {}

is a lot quicker and, in my experience, more commonly used, so it's probably best to adopt the 'standard' and save some typing.


These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.


Var Obj = {};

This is the most used and simplest method.

Using

var Obj = new Obj() 

is not preferred.

There is no need to use new Object().

For simplicity, readability and execution speed, use the first one (the object literal method).


The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...


This is essentially the same thing. Use whatever you find more convenient.


The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...


I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.


Array instantiation performance

If you wish to create an array with no length:

var arr = []; is faster than var arr = new Array();

If you wish to create an empty array with a certain length:

var arr = new Array(x); is faster than var arr = []; arr[x-1] = undefined;

For benchmarks click the following: https://jsfiddle.net/basickarl/ktbbry5b/

I do not however know the memory footprint of both, I can imagine that new Array() takes up more space.


This is essentially the same thing. Use whatever you find more convenient.


I believe {} was recommended in one of the Javascript vids on here as a good coding convention. new is necessary for pseudoclassical inheritance. the var obj = {}; way helps to remind you that this is not a classical object oriented language but a prototypal one. Thus the only time you would really need new is when you are using constructors functions. For example:

var Mammal = function (name) {
  this.name = name;
};

Mammal.prototype.get_name = function () {
  return this.name;
}

Mammal.prototype.says = function() {
  return this.saying || '';
}

Then it is used like so:

var aMammal = new Mammal('Me warm-blooded');
var name = aMammal.get_name();

Another advantage to using {} as oppose to new Object is you can use it to do JSON-style object literals.


This is essentially the same thing. Use whatever you find more convenient.


These have the same end result, but I would simply add that using the literal syntax can help one become accustomed to the syntax of JSON (a string-ified subset of JavaScript literal object syntax), so it might be a good practice to get into.

One other thing: you might have subtle errors if you forget to use the new operator. So, using literals will help you avoid that problem.

Ultimately, it will depend on the situation as well as preference.


This is essentially the same thing. Use whatever you find more convenient.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to javascript-objects

Cannot read property 'style' of undefined -- Uncaught Type Error Is this a good way to clone an object in ES6? What’s the difference between “{}” and “[]” while declaring a JavaScript array? Comparing two arrays of objects, and exclude the elements who match values into new array in JS Converting JavaScript object with numeric keys into array From an array of objects, extract value of a property as array How to copy JavaScript object to new variable NOT by reference? Remove property for all objects in array Using curl POST with variables defined in bash script functions How to sum the values of a JavaScript object?

Examples related to new-operator

Java FileOutputStream Create File if not exists How to add to an existing hash in Ruby Expression must have class type Why should C++ programmers minimize use of 'new'? Creating an object: with or without `new` int *array = new int[n]; what is this function actually doing? Open button in new window? How to open in default browser in C# Print in new line, java Deleting an object in C++