JavaScript uses **prototypal inheritance**. When you access a property, the engine first looks on the object itself, then walks up the **prototype chain** until found or null is reached. `Object.prototype` is at the top. Every function has a `.prototype` property used when constructors create instances.
1Understanding Prototypes
JavaScript uses prototypal inheritance. When you access a property, the engine first looks on the object itself, then walks up the prototype chain until found or null is reached. Object.prototype is at the top. Every function has a .prototype property used when constructors create instances.
Object.create(null) creates an object with no prototype — useful for pure hash maps without inherited methods like toString().
function Vehicle(type) { this.type = type; }
Vehicle.prototype.describe = function() {
return `I am a ${this.type}`;
};
const car = new Vehicle('car');
console.log(car.describe()); // I am a car
console.log(car.hasOwnProperty('type')); // true
console.log(car.hasOwnProperty('describe')); // false (on proto)2Practical Example
Here is a real-world application of Prototypes showing how it is used in production JavaScript code.
// Prototype chain lookup
const animal = { breathes: true };
const dog = Object.create(animal);
dog.name = 'Rex';
console.log(dog.name); // Rex (own)
console.log(dog.breathes); // true (from animal prototype)
const chain = [];
let proto = dog;
while (proto) { chain.push(proto); proto = Object.getPrototypeOf(proto); }
console.log(chain.length); // 3: dog, animal, Object.prototype3Best Practices
Follow these guidelines when working with Prototypes:
1. Use Object.getPrototypeOf() instead of __proto__
2. Add shared methods to Constructor.prototype (not instance)
3. Use hasOwnProperty() to check own vs inherited properties
Tip: Object.create(null) creates an object with no prototype — useful for pure hash maps without inherited methods like toString().
function Vehicle(type) { this.type = type; }
Vehicle.prototype.describe = function() {
return `I am a ${this.type}`;
};
const car = new Vehicle('car');
console.log(car.describe()); // I am a car
console.log(car.hasOwnProperty('type')); // true
console.log(car.hasOwnProperty('describe')); // false (on proto)