Question 40
Question
What is the difference between Object.create(null) and {}?
Answer
Object.create(null):
- Creates an empty object with no prototype chain. This means it won't inherit properties or methods from any other object. 
- Useful when you want a completely isolated object, preventing accidental inheritance conflicts. 
{} (object literal):
- Also creates an empty object, but by default, it gets set up with the - Object.prototypeas its prototype. This means:- It inherits properties and methods from - Object.prototype. For example, it will have- toString(),- hasOwnProperty(), etc., built in.
 
Key Differences:
Feature
Object.create(null)
{}
Prototype
No prototype chain
Inherits from Object.prototype
Inheritance
None
Has inherited properties/methods
When to Use Each:
- Object.create(null): When you want absolute isolation, preventing unexpected inheritance. Common use cases:- Creating utility objects where you don't want them to inherit anything from other prototypes. 
- Building your own custom object structures from scratch. 
 
- {}(object literal): In most general scenarios where you need a basic empty object, the default behavior of inheriting from- Object.prototypeis usually fine.
Last updated