Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Object.create(null) vs {}? [duplicate]

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
like image 787
Allyl Isocyanate Avatar asked May 26 '16 22:05

Allyl Isocyanate


2 Answers

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);
like image 92
Jeremy J Starcher Avatar answered Oct 20 '22 01:10

Jeremy J Starcher


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());
like image 35
Mike Cluck Avatar answered Oct 20 '22 02:10

Mike Cluck