Object.create(null)
Sometimes when you want to use a JavaScript object as a hash map (purely for storing data), you might want to create it:
var data = Object.create(null);
The difference from the simple var data = {} is that you would get a "clean" object that doesn't inherit from anything (i.e. without prototype). The effect? It will have absolutely no properties, not even constructor, toString, hasOwnProperty, etc. so you're free to use those keys in your data structure if you need to.
Example
var map1 = {},
map2 = Object.create(null);
map1.constructor
// function Object() { [native code] }
map2.constructor
// undefined
Of course you shouldn't be using reserved keywords in your code, but what if you need to build a map of elements with arbitrary keys that are entered by the user or come from a third-party API? That's where Object.create(null) may help!
Notes
-
Object.create()was introduced in ES5 [Compatibility] - ES6 will introduce new structures: Map, WeakMap and Set
References:
Written by Dmitry Pashkevich
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Prototype
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#