DEV Community

Discussion on: Javascript Object #6

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Every Object has it's own Property called Prototype.And Prototype itself is an another Object...

This isn't entirely true, it is possible to make an object without a prototype - by taking advantage of what you said - 'This Chain ends when it's Prototype is null' - we can actually start the chain with null:

// normal object
const obj1 = {}
obj1.b = 3
console.log(typeof obj1)  // object - as expected
console.log(Object.getPrototypeOf(obj1))  // Object { ... } - normal object prototype
console.log(obj1.__proto__)  // Object { ... }
console.log(obj1.b)  // 3 - object properties work normally

// prototype-less object
const obj2 = Object.create(null)
obj2.b = 3
console.log(typeof obj2)  // object - as expected
console.log(Object.getPrototypeOf(obj2))  // null
console.log(obj2.__proto__)  // undefined - nothing here! (as our object lacks the getter for __proto__)
console.log(obj2.b) //  3 - object properties work normally
Enter fullscreen mode Exit fullscreen mode

So, the object created when you use the object literal {} is actually equivalent to Object.create(Object.prototype).

Creating an object without a prototype in this manner is quite unusual, but does have some use cases. One that springs to mind is creating a very pure dictionary where there is no risk at all of property name collisions from the prototype chain - useful when you have no direct control over the property names being used, or need to use property names that already exist on the prototype. Saying that, if you find yourself in this position you may want to consider using a Map object instead as they are generally faster and consume - IIRC - less memory.

Collapse
 
samr profile image
sams-engine

You really taught me something, as a novice i will get bettter everyday.
Thanks for your corrections and keep supporting me by reading me posts.
Grateful Time! Brother