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
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With