Sub topic 19
Objects Without a Prototype: Object.create(null)
This chapter assumes you already know how Object.create(proto) sets an object's [[Prototype]], how lookup walks the prototype chain, and how Object.hasOwn differs from the in operator. Here we pass null as the prototype. The result is an object with no chain at all, and that is useful when you need a plain key-value store.
What Object.create(null) Produces
An ordinary object literal such as {} is linked to Object.prototype. Because of that link it inherits toString, hasOwnProperty, constructor, the __proto__ accessor, and other members. Object.create(null) creates an object whose [[Prototype]] is null. Its chain ends right away.
const dict = Object.create(null);
dict.apple = 3;
console.log(Object.getPrototypeOf(dict)); // null
console.log(dict.toString); // undefined
console.log('toString' in dict); // false
console.log(Object.keys(dict)); // ['apple']Property lookup on dict checks the object's own properties, finds nothing else to check, and returns undefined. The only keys dict will ever report are the ones you put there.
You can also create one with literal syntax. Inside an object literal, __proto__: value sets the prototype. It does not create a property:
const config = { __proto__: null, mode: 'strict' };
console.log(Object.getPrototypeOf(config)); // null
console.log(Object.keys(config)); // ['mode']Why Inherited Keys Break Dictionaries
If you use a plain object as a dictionary, the inherited names collide with your data. Two kinds of collision cause problems. The first is that in and simple truthiness checks report keys you never added. The second is that __proto__ is an accessor on Object.prototype, so writing to it calls a setter. The write does not store a value.
The following word counter shows both problems:
function countWords(words, store) {
for (const w of words) {
store[w] = (store[w] || 0) + 1;
}
return store;
}
const words = ['constructor', '__proto__', 'apple', 'apple'];
const plain = countWords(words, {});
console.log(typeof plain.constructor); // 'string' (inherited Object function + 1)
console.log(Object.keys(plain)); // ['constructor', 'apple']: '__proto__' was lost
const safe = countWords(words, Object.create(null));
console.log(safe.constructor); // 1
console.log(safe['__proto__']); // 1
console.log(Object.keys(safe)); // ['constructor', '__proto__', 'apple']With {}, reading store['constructor'] returns the inherited Object function. Adding 1 to it concatenates strings. Reading store['__proto__'] returns Object.prototype. Assigning a string to it goes through the setter, which ignores values that are not objects, so the count disappears. With the null-prototype store, '__proto__' and 'constructor' are ordinary keys.
A Defense Against Prototype Pollution
Prototype pollution is an attack where untrusted input writes to Object.prototype, which changes every ordinary object in the program. A common way in is a naive recursive merge of parsed JSON. JSON.parse creates "__proto__" as a real own property, and a later bracket access on a normal object follows it to Object.prototype:
function merge(target, source, makeObject) {
for (const key of Object.keys(source)) {
const value = source[key];
if (value && typeof value === 'object') {
if (!target[key] || typeof target[key] !== 'object') target[key] = makeObject();
merge(target[key], value, makeObject);
} else {
target[key] = value;
}
}
return target;
}
const payload = JSON.parse('{"__proto__": {"isAdmin": true}}');
merge({}, payload, () => ({}));
console.log({}.isAdmin); // true: Object.prototype was polluted
delete Object.prototype.isAdmin; // clean up
const result = merge(Object.create(null), payload, () => Object.create(null));
console.log({}.isAdmin); // undefined
console.log(result['__proto__']); // [Object: null prototype] { isAdmin: true } in Node.jsIn the safe version, target['__proto__'] is undefined, so the merge creates an own property and recurses into it. The nested objects must also have null prototypes. A single nested {} would bring the hole back.
The Costs: Missing Methods
The object has no prototype, so every method you normally inherit is gone. These are the usual surprises:
const d = Object.create(null);
d.a = 1;
console.log(Object.hasOwn(d, 'a')); // true
console.log(Object.prototype.hasOwnProperty.call(d, 'a')); // true (older alternative)
console.log(JSON.stringify(d)); // '{"a":1}'
console.log({ ...d }); // { a: 1 } (a normal object again)
try {
d.hasOwnProperty('a');
} catch (e) {
console.log(e.constructor.name); // 'TypeError': d.hasOwnProperty is not a function
}
try {
console.log(`${d}`);
} catch (e) {
console.log(e.message); // Cannot convert object to primitive value
}String conversion fails because the object has no toString or valueOf to call. Logging libraries and template strings that format arbitrary values can therefore throw. Static helpers such as Object.keys, Object.entries, Object.hasOwn, and JSON.stringify work normally, because they do not depend on the object's chain. for...in also works, and it lists only own enumerable keys because there is nothing to inherit.
Choosing Between a Null-Prototype Object and a Map
| Need | `{}` | `Object.create(null)` | `Map` |
|---|---|---|---|
| No inherited keys | No | Yes | Yes |
| `__proto__` stored as a normal key | No | Yes | Yes |
| Keys other than strings and symbols | No | No | Yes |
| Serializes directly with `JSON.stringify` | Yes | Yes | No |
| Size available in O(1) | No | No | Yes (`size`) |
| Built-in methods such as `toString` | Yes | No | Yes |
Pick a null-prototype object when the data has string keys, must serialize to JSON, or gets passed to code that expects plain objects, such as options bags or lookup tables built at startup. Pick a Map when keys are added and removed often, when keys are not strings, or when you need the entry count.
Exercise
You build a cache with const cache = {} and check if (cache[key]) return cache[key];. A user requests the key "toString". What happens, and what is the smallest change that fixes it?
Show answer
cache['toString'] finds the inherited Object.prototype.toString function, which is truthy, so the code returns a function instead of a cached value. Create the cache with Object.create(null) so nothing is inherited. Better still, check with Object.hasOwn(cache, key), which also handles cached values that are falsy.
Exercise
Given const d = Object.create(null); d.x = 1;, which of these throw: Object.keys(d), String(d), JSON.stringify(d), d.valueOf(), 'x' in d?
Show answer
String(d) throws a TypeError because there is no toString or valueOf to convert with. d.valueOf() throws a TypeError because d.valueOf is undefined. Object.keys(d) returns ['x'], JSON.stringify(d) returns '{"x":1}', and 'x' in d is true.
Exercise
Why does { __proto__: null } create a null-prototype object, while const o = {}; o.__proto__ = null; and JSON.parse('{"__proto__": null}') behave differently from each other?
Show answer
In an object literal, __proto__: value is special syntax that sets [[Prototype]]. o.__proto__ = null calls the inherited setter on Object.prototype, which also sets the prototype to null, but only because o still had that accessor at the time of the assignment. JSON.parse defines an ordinary own data property named "_proto_" and leaves the prototype as Object.prototype.