I understand that using Object.create(null)
creates an object which has no proto
property (i.e. Object.getPrototypeOf( myObj ) === null
) but can someone help me understand what are some of the use cases for this?
In other words, why would you want to create an object that is completely empty (i.e. doesn't inherit any methods from Object.prototype
)?
You can use such an object for a key-value map. Without the prototype chain, you can be sure that things like
.toString()
do not unwittingly exist on the object. That means you can incautiously access properties on it, and you can use thein
operator instead ofObject.prototype.hasOwnProperty.call
.In very rare instances where something may have been added to
Object.prototype
It may be better to create an Object with
Object.create(null)
as it won't inherit this, considerThis means you don't have to worry for example if you've used a
for..in
loopFurthermore, you can make it so you fail
instanceof
testsThis is because
instanceof
is basically testing the prototype chain against the RHS, and there is no such chain.