Pure object without prototype
In JavaScript, a "pure object" (or object dictionary) -
is an object without a prototype, that is, without Object.prototype and all its built-in methods (toString, hasOwnProperty, etc.).
Such an object is ideal for pure data stores (dictionaries, maps), where you want to be sure that no built-in properties clash with your keys.
How to create a pure object
The simplest and correct way
const obj = Object.create(null);This creates an object without a prototype,
that is, obj.__proto__ === undefined and Object.getPrototypeOf(obj) === null.
Let's check
const obj = Object.create(null);
console.log(Object.getPrototypeOf(obj)); // null
console.log('__proto__' in obj); // false
console.log(typeof obj.toString); // undefinedSuch an object has no inheritance chain -
it does not inherit even from Object.prototype.
Why this is useful
Regular objects inherit a bunch of built-in methods:
const normal = {};
console.log(Object.getPrototypeOf(normal) === Object.prototype); // true
// These methods are available
console.log(normal.hasOwnProperty); // [Function]
console.log(normal.toString); // [Function]This can be dangerous if keys clash with these names:
const map = {};
map.toString = 'value'; // can break code if someone calls map.toString()A "pure object" solves this problem:
const map = Object.create(null);
map.toString = 'value'; // just a key
console.log(map.toString); // "value"Example usage - "dictionaries" or "maps"
const dict = Object.create(null);
dict.apple = 1;
dict.banana = 2;
dict['__proto__'] = 3; // safe, does not affect the prototype
console.log(dict.apple); // 1
console.log(dict['__proto__']); // 3In regular objects __proto__ has special behavior,
but here it's just a regular property.
Drawback
A "pure" object has no built-in methods:
const obj = Object.create(null);
obj.name = 'Alice';
console.log(obj.hasOwnProperty('name')); // Error: hasOwnProperty is not a functionIf you need to check whether a property exists, use the safe way:
console.log(Object.prototype.hasOwnProperty.call(obj, 'name')); // trueAlternative - use Map
A modern way to store dictionaries:
const map = new Map();
map.set('apple', 1);
map.set('__proto__', 2);
console.log(map.get('__proto__')); // 2Map solves the same task,
but stores data with any keys (including objects).
SUMMARY
| Method | Prototype | Access to built-in methods | Suitable for dictionaries |
|---|---|---|---|
{} | Object.prototype | Yes (toString, hasOwnProperty) | No |
Object.create(null) | null | No | Yes |
new Map() | not an object | Methods set, get, has | Yes (modern option) |
In one phrase:
To create a "pure object" without
Object.prototype, usejavascriptconst obj = Object.create(null);
- it inherits nothing, and is ideal for safe dictionaries.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.