Mastering Shadowing Properties in JavaScript Inheritance

A Practical Guide to Understanding a Crucial Concept

Max N
3 min readApr 4, 2024

In the world of JavaScript, understanding inheritance and the concept of shadowing properties is crucial for writing clean, maintainable code. Shadowing properties can lead to unexpected behavior, and it’s essential to grasp how it works to avoid potential bugs and ensure your code functions as intended.

Let’s start with a simple example:

class Animal {
constructor(name) {
this.name = name;
}

speak() {
console.log(`${this.name} makes a sound.`);
}
}

class Dog extends Animal {
constructor(name) {
super(name);
}

speak() {
console.log(`${this.name} barks.`);
}
}

const animal = new Animal('Fluffy');
const dog = new Dog('Buddy');

animal.speak(); // Fluffy makes a sound.
dog.speak(); // Buddy barks.

In this example, we have a base class Animal and a derived class Dog that inherits from Animal. Both classes have a speak method, but they behave differently because of shadowing properties.

When you create an instance of Dog and call its speak method, the speak method defined in the Dog class is executed, not the one from the Animal class. This is because the speak method in the Dog class "shadows" or overrides the speak method in the…

--

--

Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.