Back to Blog
JavaScript

What is Inheritance in JavaScript?

27 February 20251 min read1 views
What is Inheritance in JavaScript?

Description: Learn about inheritance in JavaScript, including prototypal and class-based inheritance, with examples.

Description:

Inheritance is a fundamental concept in object-oriented programming that allows one class (child) to inherit properties and methods from another class (parent). JavaScript supports both prototypal inheritance and class-based inheritance.

Explanation:

In JavaScript, inheritance helps in reusing code by creating a new class from an existing class. Prior to ES6, JavaScript relied on prototype-based inheritance, but ES6 introduced the class keyword, making it easier to work with OOP concepts.

With prototypal inheritance, objects inherit properties and methods from another object using Object.create(). With class-based inheritance, we use the extends keyword to define a subclass.

Here’s an example demonstrating class-based inheritance in JavaScript:

// Parent class
class Animal {
    constructor(name) {
        this.name = name;
    }
    speak() {
        console.log(`${this.name} makes a noise`);
    }
}

// Child class inheriting from Animal
class Dog extends Animal {
    speak() {
        console.log(`${this.name} barks`);
    }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks

This allows Dog to inherit from Animal, ensuring code reusability and cleaner structure.

Was this article helpful?

C

Written by

CoderCrafter Team

Developer & Technical Writer

Building developer tools and writing practical engineering content at CoderCrafter. Covers JavaScript, React, Node.js, DevOps, and modern web development.

Comments

Leave a comment

0/2000

Comments are reviewed before appearing. Be kind and constructive.

Call UsWhatsApp