The null object which is *actually* an object
Disclaimer: rushed post tonight — xmas eve and all — learn from me at your own risk.
While reading Why Prototypal Inheritance Matters by Aadit M Shah, I had to pause on this variable declaration when I read it in:
let emptyObject = Object.create(null)
// using Object.create(null) yields an object with zero properties; if you’re relatively new to JS, you may have never seen this before. Test it in your console and see what that looks like.
The object which should be the prototype of the newly-created object.
…(I didn’t include this because it’s not relevant right now)
The proto parameter has to be either
an Object excluding primitive wrapper objects.
Ok, so I’m fine with this: we want a way to create an object that doesn’t inherit from the Object prototype, so even though we’re passing as an argument something that’s NOT an object to a parameter which otherwise takes only object arguments, since this is real the “proto” parameter and the end of the JS prototype chain is “null,” this makes sense from a definitional perspective, if not from a “keep the data-type of your arguments consistent” perspective.
We are creating an object with a prototype of null, similar to Object, only this one doesn’t have the built-in JS object properties. Put another way, in the hierarchy of prototype inheritance, we can sort of think about Object and Object.create(null) as being at the same level of hierarchy: above them in the prototype chain is only null, which is essentially nothing, the end of the line.
Further Topics to explore
- Object.create vs. Object.assign
- what it means to have an empty object
- what this demonstrates about prototypal inheritance
- Is there a use case for Object.create(null) or is this just something interesting in JS, but we don’t have to know about Object.create in depth because we would never do this in practice, and a template literal object definition whose prototype is Object would always be a lot more useful in practice? I saw one article talking about how if using an object as a map, having it be emptied of the default Object properties could prevent problems (which might occur if a key in the map had the same name as a default Object property)
- Personally I feel like I can see some benefit to creating simple objects that don’t inherit any properties from Object, but MDN spent a lot of time covering bugs that can arise from using Object.create(null)
- How does prototypal inheritance connect to React? Is this why that dude at Roman says Class components don’t fly and it’s better to use functional components + hooks instead of Redux etc?
- Let’s look at some prototype-related methods under the hood:
- factory functions