6

Is there a difference between objects created via the Object.create(null) syntax, vs the {} syntax?

From the node v5.6.0 REPL:

> var a = Object.create(null)
undefined
> var b = {}
undefined
> a == b
false
> a.prototype
undefined
> b.prototype
undefined
Allyl Isocyanate
  • 13,306
  • 17
  • 79
  • 130
  • Only functions have a `prototype` property by default. That has nothing to do with the actual (internal) prototype of an object. What you want to use is `Object.getPrototypeOf(a)` and `Object.getPrototypeOf(b)`. – Felix Kling May 26 '16 at 22:23

2 Answers2

9

Objects made from Object.create(null) are totally empty -- they do not inherit anything from Object.prototype.

Empty objects do.

In the following example, I'm checking for the property of toString

var fromNull = Object.create(null);
console.log(typeof fromNull.toString);
var emptyObject = {};
console.log(typeof emptyObject.toString);
Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
5

There is a difference.

With {} you create an object who's prototype is Object.prototype. But doing Object.create(null) creates an object who's prototype is null.

On the surface, they appear to be the same but in the latter case, you don't inherit basic functions attached to the Object prototype.

var objPrototype = {};
console.log(objPrototype.toString());
var nullPrototype = Object.create(null);
console.log(nullPrototype.toString());
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91