Built-in chains and a dictionary with no prototype
A null-prototype object inherits nothing, so a key like toString or __proto__ can't collide with a built-in. Map is usually even better for dictionaries.
Every object has a hidden link to another object, its prototype; when you read a property the object doesn't have, JavaScript follows that link, and the next one, up the prototype chain until it finds the property or reaches null.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Create const vehicle = { wheels: 4, info() { return this.type + " with " + this.wheels + " wheels"; } }. Make bike from it with Object.create, give it type: "bike" and its own wheels: 2, and print bike.info() and vehicle.wheels.
Write a function isInherited(obj, key) that returns true only when key can be read on obj but isn't an own property. Test it with [] and "map", and with { a: 1 } and "a".
Write a function depth(obj) that returns how many links there are from obj to null. What does it return for {}, [] and Object.create(null)?
Explain it without notes
What is the prototype chain, and how does property lookup use it?
What is the difference between __proto__, Object.getPrototypeOf and a function's prototype property?
What happens when you assign a property that already exists on the prototype?
Why and when would you use Object.create(null)?
Preview
Console
Nothing logged yet.Expected console output
[1, 2]: Array.prototype -> Object.prototype -> null
function: Function.prototype -> Object.prototype -> null
new Map(): Map.prototype -> Object.prototype -> null
{}: Object.prototype -> null
false true
[Object: null prototype] { apple: 3 }