Last Updated: February 25, 2016
·
1.688K
· dpashkevich

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

References: