JavaScript Prototypes and Classes Explained
Prototypes underpin all JavaScript objects. Here's what interviews test — prototype chain, class syntax, and inheritance.
The prototype chain
Every JavaScript object has a prototype. When you access a property, JavaScript searches the object, then its prototype, then up the chain.
const animal = {
breathe() { return "breathing"; }
};
const dog = Object.create(animal);
dog.bark = function() { return "woof"; };
dog.bark(); // "woof" — own property
dog.breathe(); // "breathing" — from prototype
// Check the chain:
Object.getPrototypeOf(dog) === animal; // true
dog.hasOwnProperty("bark"); // true
dog.hasOwnProperty("breathe"); // falseClass syntax
ES6 classes are syntactic sugar over prototypes. They look like Java/Python but behave like JavaScript prototypes under the hood.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
static create(name) {
return new Animal(name);
}
}
const cat = new Animal("Cat");
cat.speak(); // "Cat makes a sound"
Animal.create("Dog"); // static — called on class, not instanceInheritance with extends and super
extends creates a child class. super() must be called in the child constructor before using this.
class Dog extends Animal {
constructor(name, breed) {
super(name); // MUST call super first
this.breed = breed;
}
speak() {
return `${super.speak()} — specifically, woof`;
}
}
const rex = new Dog("Rex", "Labrador");
rex.speak();
// "Rex makes a sound — specifically, woof"
rex instanceof Dog; // true
rex instanceof Animal; // trueGetters and setters
Getters and setters let you define computed properties and validation logic.
class Circle {
constructor(radius) {
this._radius = radius;
}
get radius() { return this._radius; }
set radius(value) {
if (value < 0) throw new Error("Radius must be positive");
this._radius = value;
}
get area() {
return Math.PI * this._radius ** 2;
}
}
const c = new Circle(5);
c.radius = 10; // uses setter
console.log(c.area); // uses getter, no ()Exam tip
The most common prototype question: "What does Object.create() do?" — it creates a new object with the specified prototype, without calling a constructor. Also know that class extends translates to prototype chain inheritance.
Think you're ready? Prove it.
Take the free JavaScript readiness test. Get a score, topic breakdown, and your exact weak areas.
Take the free JavaScript test →Free · No sign-up · Instant results