In JavaScript, you can create an object without a prototype using Object.create(null). This method creates a plain object that does not inherit from Object.prototype, meaning it won’t have built-in methods like toString(), hasOwnProperty(), etc., which are typically inherited from the prototype chain.
const obj = Object.create(null);
obj.name = "No Prototype Object";
obj.age = 99;
console.log(obj);
console.log(obj.toString);
console.log(obj.hasOwnProperty);
Output
[Object: null prototype] { name: 'No Prototype Object', age: 99 }
undefined
undefined
Explanation
- When you create an object using Object.create(null), it has no prototype, meaning it does not inherit from Object.prototype.
- The resulting object is a "clean slate" with no inherited properties or methods.
Comparison with a Standard Object
const obj = {};
console.log(obj.toString);
console.log(obj.hasOwnProperty('key'));
Output
[Function: toString] false
A regular object created with {} inherits properties and methods from Object.prototype.
Why Create an Object Without a Prototype?
Prototype-less objects are objects that do not inherit from Object.prototype. By default, most objects in JavaScript come with built-in methods such as toString(), hasOwnProperty(), and others, which can lead to unintended conflicts when using the object as a dictionary or map.
Here are a few reasons why you might want to create an object without a prototype
- Pure Dictionary Usage: If you want a simple key-value store with no inherited properties or methods.
- Avoiding Conflicts: Prevent accidental overwriting of properties like toString, valueOf, etc., that exist on Object.prototype.
- Performance Considerations: Prototype-less objects might have a slight performance advantage in some use cases due to a lack of inherited overhead.
Using a Prototype-less Object as a Dictionary -Use Case
We can use a prototype-less object is to create a dictionary or map where keys are string values. By avoiding inheritance, you ensure that only your defined keys are present, with no risk of conflicts from built-in properties.
const dict = Object.create(null);
dict.apple = "A fruit";
dict.car = "A vehicle";
console.log(dict);
console.log(dict.toString);
Output
[Object: null prototype] { apple: 'A fruit', car: 'A vehicle' }
undefined
Key Considerstion while using Prototype-less objects
- Lack of Built-In Methods: Prototype-less objects do not have methods like toString(), hasOwnProperty(), or valueOf(). If you need these methods, you will need to add them manually.
- Not Suitable for All Use Cases: Prototype-less objects are ideal for dictionary-like structures but may not be appropriate for objects requiring common methods like toString(), toLocaleString(), etc.
- Potential Performance Differences: Depending on the context, prototype-less objects may offer slight performance gains due to the absence of prototype chain traversal. However, this is often negligible in everyday cases.