Search code examples
javascriptjavascript-objects

Is Object.create(null) different from {} while defining __proto__ as null?


There seems to be a common approach to creating bare objects in javascript which is to use

Object.create(null)

to create an object without any pre-existing attributes. Is this any different from doing

var obj = {}
obj.__proto__ = null

or are they functionally identical? If the purpose of doing this is to use an object as a hashmap, would there be any change in performance or functionality between the two if proto was set to null after adding key-value pairs?


Solution

  • Yes they do basically the same.

    would there be any change in performance?

    As MDN concludes on obj.__proto__:

    Warning: Changing the [[Prototype]] of an object is, by the nature of how modern JavaScript engines optimize property accesses, a very slow operation, in every browser and JavaScript engine. The effects on performance of altering inheritance are subtle and far-flung, and are not limited to simply the time spent in obj.__proto__ = ... statement, but may extend to any code that has access to any object whose [[Prototype]] has been altered.

    So you should definetly use Object.create(null) ...