Problem Statement
What is at the end of every prototype chain?
Explanation
The prototype chain ends with null.
Every object ultimately inherits from Object.prototype. The prototype of Object.prototype is null, which marks the end.
When JavaScript looks for a property, it goes up the chain until it finds the property or reaches null.
Reaching null means the property does not exist anywhere in the chain.
Understanding the prototype chain explains how inheritance and property lookup work in JavaScript.
This is a common interview question testing deep knowledge of prototypes.
Code Solution
SolutionRead Only
// Prototype chain visualization
const obj = {};
// obj -> Object.prototype -> null
console.log(Object.getPrototypeOf(obj)); // Object.prototype
console.log(Object.getPrototypeOf(Object.prototype)); // null
// Array prototype chain
const arr = [];
// arr -> Array.prototype -> Object.prototype -> null
console.log(Object.getPrototypeOf(arr)); // Array.prototype
console.log(Object.getPrototypeOf(Array.prototype)); // Object.prototype
console.log(Object.getPrototypeOf(Object.prototype)); // null
// Function prototype chain
function myFunc() {}
// myFunc -> Function.prototype -> Object.prototype -> null
console.log(Object.getPrototypeOf(myFunc)); // Function.prototype
console.log(Object.getPrototypeOf(Function.prototype)); // Object.prototype
console.log(Object.getPrototypeOf(Object.prototype)); // null
// Property lookup example
const person = {
name: 'John'
};
// Looking for toString
// 1. Check person - not found
// 2. Check Object.prototype - found!
console.log(person.toString()); // '[object Object]'
// Looking for nonExistent
// 1. Check person - not found
// 2. Check Object.prototype - not found
// 3. Reach null - return undefined
console.log(person.nonExistent); // undefined