417

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()
Alireza
  • 100,211
  • 27
  • 269
  • 172
Jonas Pegerfalk
  • 9,016
  • 9
  • 29
  • 29
  • 7
    Warning: there is a minor difference which could cause very irritating bugs! Creating an empty object assigning it to "{}" in an Object prototype will be the same Object instance in every Object instance created by a "new" operator. While do you use "new Object({})", you will have different instances. – peterh Jan 16 '15 at 11:35
  • Worth to mention that in addition to `var objectA = {} var objectB = new Object()` there is a third construct which will produce the same result: `var objectC = Object.create(Object.prototype);` – kalitsov Sep 26 '16 at 05:37
  • `{}` and `[]` Use `{}` instead of `new Object()`. Use `[]` instead of `new Array()`. Use arrays when the member names would be sequential integers. Use objects when the member names are arbitrary strings or names. [source](http://javascript.crockford.com/code.html) – ilgaar Jun 03 '17 at 11:49
  • 2
    `new Object()` and `{}` are not quite empty objects, they are objects that have the Object.prototype. You can use `Object.create(null)` for a truly empty object (at least according to the mozilla docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create) –  Oct 07 '19 at 04:11

10 Answers10

510

Objects

There is no benefit to using new Object(), whereas {} can make your code more compact, and more readable.

For defining empty objects they're technically the same. The {} syntax is shorter, neater (less Java-ish), and allows you to instantly populate the object inline - like so:

var myObject = {
  title: 'Frog',
  url: '/img/picture.jpg',
  width: 300,
  height: 200
};

Arrays

For arrays, there's similarly almost no benefit to ever using new Array() over [] — with one minor exception:

var emptyArray = new Array(100);

creates a 100 item long array with all slots containing undefined, which may be nice/useful in certain situations (such as (new Array(9)).join('Na-Na ') + 'Batman!').

My recommendation

  1. Never use new Object(); — it's clunkier than {} and looks silly.
  2. Always use [] — except when you need to quickly create an "empty" array with a predefined length.
Már Örlygsson
  • 14,176
  • 3
  • 42
  • 53
  • 24
    Even if you use the Array(100) syntax, that same array, at the 101st position has undefined in it; the only thing that number really does is change the value of the length property. – Jason Bunting Oct 31 '08 at 03:45
  • Yes. new Array(100); is a nice one-liner way to do that. ....ah... I see that I'd accidentally left in the word "important" ... will edit that out. – Már Örlygsson Oct 31 '08 at 11:48
  • `Array(100)` is just wrong, it leaves the array in an invalid state since it's length is 100, and it's equal to `[]` until you start adding stuff __don't do this__ – Pablo Fernandez Aug 20 '11 at 15:21
  • 6
    @Pablo there's nothing invalid about `new Array(100)`. Read the literature: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array – Már Örlygsson Aug 20 '11 at 17:09
  • @Már take it from someone who knows what he's talking about: http://javascript.crockford.com/code.html#bonus – Pablo Fernandez Aug 20 '11 at 17:22
  • 9
    @Pablo I have no idea what your argument is. Like Douglas Crockford, I recommend using `[]`. No argument there. You, however, argued that `new Array(100)` is somehow "invalid", which is untrue. – Már Örlygsson Aug 23 '11 at 10:59
  • This 'answer' is really just an opinion, and ignores the actual differences as stated by Guillermo. – A.R. Nov 20 '13 at 17:41
  • 2
    The OP asks about creating empty objects. Guillermo points out differences when creating non-empty objects, which is correct but not quite what the OP asked about. – Már Örlygsson Nov 25 '13 at 17:47
  • 2
    `new Array(len).fill(0);` – Muhammad Umer Oct 11 '14 at 21:26
  • 11
    Also, be aware that `new Array(1,2,3)` results in `[1,2,3]`, but `new Array(1)` does *not* result in `[1]`; thus, the semantics of `Array` are inconsistent and unnecessarily confusing. – Dancrumb Dec 29 '14 at 14:56
  • 1
    There is a very important difference: if you create an empty object by simply assigning it to "{}", it will be the same. If you create it with "new Object({})" it will be a different object instance everywhere... – peterh Jan 16 '15 at 11:34
  • Be aware that you can set the "length" property of an array like so: `var a = []; a.length = 10;` which would make the array be of 10 undefined elements. – jaySon Oct 25 '15 at 20:24
  • 1
    I find new Object() to be more readable than {}. Saying it's klunky and silly just sounds elitist to me. – Mark May 04 '16 at 19:39
  • 4
    I'd add that `Object.create(null)` can be useful for creating a blank object, whereas `{ }` inherits from the Object prototype. – Meow Sep 15 '16 at 18:45
  • Be careful with `new Array(len).fill(0)` when you fill an object, for example: with `Array(len).fill([ ])` it will reference the same "[ ]", then if you do something like `let a = Array(len).fill([])` and then `a[0].push(1)` it will be pushed to all the elements in the array. – miguelps Jan 15 '21 at 23:42
104

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.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Guillermo Snipe
  • 1,049
  • 1
  • 7
  • 2
  • 1
    Literal notation is in fact more readable and concise to create dynamic data objects. – Sid Aug 06 '17 at 08:35
  • Very detail oriented comment. You didn't put the code just for the sake of it. Instead tried to explain the difference and the important thing that when to use which statement. Thanks! – Ali Hassan Cheema Nov 04 '22 at 21:35
14

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.

Jason Bunting
  • 58,249
  • 14
  • 102
  • 93
10
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.

Bobby Jack
  • 15,689
  • 15
  • 65
  • 97
9

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.

basickarl
  • 37,187
  • 64
  • 214
  • 335
  • `arr = new Array(x)` is equivalent to `arr = []; arr.length = x;`, not to assigning the `x-1` index with `undefined`. – Bergi Apr 30 '18 at 18:33
8

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...

bobince
  • 528,062
  • 107
  • 651
  • 834
8

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.

Thedric Walker
  • 1,817
  • 15
  • 23
4
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).

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Amit Singh
  • 279
  • 2
  • 7
  • How does this answer the original questions? _"Is there any difference in how the script engine handles them? Is there any reason to use one over the other?"_ – Zsolt Meszaros Dec 04 '20 at 10:32
  • There is no need to use new Object(). For simplicity, readability and execution speed, use the first one (the object literal method). – Amit Singh Dec 04 '20 at 11:28
2

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

Tomalak
  • 332,285
  • 67
  • 532
  • 628
  • Perhaps I'm delving too deep into javascript here, but are they the same? Isn't the {proto} of `Object` is null, while the {proto} of `{}` is 'Object.prototype'? – Izhaki May 08 '14 at 22:10
  • @Izhaki The prototype of `Object` is null, that's correct. That's because `Object` terminates the prototype chain. Object *instances* however don't have a prototype, only constructors have one. And `(new Object()).constructor === ({}).constructor` -> `true` – Tomalak May 09 '14 at 00:04
  • So [this](http://zeekat.nl/articles/constructors-considered-mildly-confusing.html#sec-3-3) is incorrect then? – Izhaki May 09 '14 at 00:40
  • Here's my point: `new Object()` yields a blank Object instance. `{}` yields a blank Object instance. Both of these instances are absolutely indistinguishable. The example you link to does something else (it modifies the prototype chain) and doesn't really apply here - or I don't understand your argument. – Tomalak May 09 '14 at 07:19
2

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!

Alireza
  • 100,211
  • 27
  • 269
  • 172