8

If you create a regular javascript object using say var obj = {}; it will have the object prototype. Same goes for objects created using var obj = new MyClass(); Before Object.create was introduced there was no way around this. However nowadays it's possible to create an object with no prototype (respectively null as its prototype) using var obj = Object.create(null);.

Why is this important? What advantages does it bring? Are there any real world use cases?

Wingblade
  • 9,585
  • 10
  • 35
  • 48
  • 2
    Same as mentioned in answer: http://www.devthought.com/2012/01/18/an-object-is-not-a-hash/ For making sure no clashes with inherited properties. – Aravind Nov 16 '14 at 20:26

2 Answers2

11

It's a completely empty object (nothing inherited from any .prototype including Object.prototype), so you can be guaranteed that any property lookup will only succeed if the property was explicitly added to the object.

For example, if you want to store some data where you won't know the keys in advance, there's a possibility that a provided key will have the same name as a member of Object.prototype, and cause a bug.

In those cases, you need to do an explicit .hasOwnProperty() check to rule out unexpected inherited values. But if there's nothing inherited, your testing can be simplified to a if (key in my_object) { test, or perhaps a simple truthy test if (my_object[key]) { if appropriate.

Also, with no prototype chain, I would imagine that lookups of properties that turn out to not exist would be faster, since only the immediate object would need to be checked. Whether or not this pans out in reality (due to optimizations) would be determined with performance testing.

noamtm
  • 12,435
  • 15
  • 71
  • 107
six fingered man
  • 2,460
  • 12
  • 15
0

The only difference here between creating an object with {} and Object.create(null) is that the Object prototype will not be inherited from.

This means that any of the methods we typically assume we can call on any object will not exist, such as toString and valueOf. A list of these can be found here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype

From a performance perspective, creating an object simply by {} is actually much faster, so unless you specifically cannot have the functions under the Object prototype you should not create objects in that manner.

http://jsperf.com/null-vs-empty-object-performance

David Li
  • 1,250
  • 8
  • 18