One practical use-case of Object.create(null)

One practical use-case of Object.create(null)

Sometimes, you see Object.create(null) and don't understand why not just using {}.

After more than ten years of using javascript, I have found a relevant bug I had to use Object.create(null).


The client provides a string key and arbitrary value, you want to store list of values in an object indexed by that key. That's a simple task.

I naively do this:

const store = {}
;(store[key] ??= []).push(value)

What do you think? Does this seem good?? The answer is NO. What?? See next.


The problem comes from the fact that I initialized store as {}, an instance from Object class. store[key] checks for properties of the store object itself, if not found, it tries to find the property in its prototype chain, i.e. from Object.prototype whose keys such as constructor is not null.

To avoid this problem, you must initialize store without a prototype chain.

Happy coding and your javascript life!

Buy Me A Coffee