Skip to main content

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

javascript
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

javascript
const obj = Object.create(null); console.log(Object.getPrototypeOf(obj)); // null console.log('__proto__' in obj); // false console.log(typeof obj.toString); // undefined

Such 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:

javascript
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:

javascript
const map = {}; map.toString = 'value'; // can break code if someone calls map.toString()

A "pure object" solves this problem:

javascript
const map = Object.create(null); map.toString = 'value'; // just a key console.log(map.toString); // "value"

Example usage - "dictionaries" or "maps"

javascript
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__']); // 3

In regular objects __proto__ has special behavior, but here it's just a regular property.


Drawback

A "pure" object has no built-in methods:

javascript
const obj = Object.create(null); obj.name = 'Alice'; console.log(obj.hasOwnProperty('name')); // Error: hasOwnProperty is not a function

If you need to check whether a property exists, use the safe way:

javascript
console.log(Object.prototype.hasOwnProperty.call(obj, 'name')); // true

Alternative - use Map

A modern way to store dictionaries:

javascript
const map = new Map(); map.set('apple', 1); map.set('__proto__', 2); console.log(map.get('__proto__')); // 2

Map solves the same task, but stores data with any keys (including objects).


SUMMARY

MethodPrototypeAccess to built-in methodsSuitable for dictionaries
{}Object.prototypeYes (toString, hasOwnProperty)No
Object.create(null)nullNoYes
new Map()not an objectMethods set, get, hasYes (modern option)

In one phrase:

To create a "pure object" without Object.prototype, use

javascript
const obj = Object.create(null);
  • it inherits nothing, and is ideal for safe dictionaries.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.