JavaScript:JavaScript Class Inheritance with extends and super()
JavaScript•Inheritance

JavaScript Class Inheritance with extends and super()

Class inheritance establishes prototype chains, allowing subclasses to reuse and override parent behavior.

Syntax

class SubClass extends BaseClass { constructor(args) { super(args); } }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
extendsKeywordDesignates parent class to inherit from.
super()CallCalls parent constructor and passes initial arguments.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing JavaScript locally:

// Class Inheritance in JavaScript
class Employee {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }

  getDetails() {
    return this.name + " (" + this.department + ")";
  }
}

class Developer extends Employee {
  constructor(name, programmingLanguage) {
    super(name, "Engineering"); // Call parent constructor
    this.programmingLanguage = programmingLanguage;
  }

  // Method overriding
  getDetails() {
    return super.getDetails() + " - Specialist: " + this.programmingLanguage;
  }
}

const dev = new Developer("Sarah", "TypeScript");
console.log(dev.getDetails());
Expected Output:
Sarah (Engineering) - Specialist: TypeScript

How It Works: Step-by-Step

  • Line 11: Developer inherits properties and methods from Employee via extends.
  • Line 13: super(name, "Engineering") initializes parent constructor state.
  • Lines 18-20: Overrides getDetails() while delegating base string to super.getDetails().

Key Concepts

  • In derived classes, super() must be called before using this in constructor.
  • super.methodName() invokes the parent class implementation of an overridden method.
  • instanceof operator checks inheritance across prototype chains.

Common Mistake: Accessing this before calling super() in derived class constructor

In derived class constructors, this is uninitialized until super() has executed.

❌ Incorrect
class Child extends Parent {
  constructor(x) {
    this.x = x; // ReferenceError: Must call super constructor!
    super();
  }
}
✅ Correct
class Child extends Parent {
  constructor(x) {
    super();
    this.x = x;
  }
}

Related JavaScript Tutorials & Compiler

Run and test JavaScript on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

JavaScript Online Compiler