JS: Keyword “extends”

By Xah Lee. Date: . Last updated: .

New in ES2015.

The extends keyword is used together with the class. It creates a constructor function. And, automatically creates 2 parent/child relationships.

[see JS: Class]

Basic Example

First, here's a typical example of using extends.

// create a class
class A {
    constructor(x) {
        console.log ( "A constructor called with " + x );
        this.k1 = x;

    f () { console.log ( "f called" ) }


class B extends A {

    // adding a property in constructor
    constructor(x,y) {
        console.log ( `B constructor called with ${x} ${y}` );
        super( x ); // calls A's constructor
        this.k2 = y; // add its own property

    // add a method g
    g () { console.log ( "g called" ) }

const b = new B(3,4);
// prints
// B constructor called with 3 4
// A constructor called with 3

console.log ( b ); // B { k1: 3, k2: 4 }

b.f(); // prints: f called
b.g(); // prints: g called

// this works because
// parent of b is B.prototype, which contains function g
// parent of B.prototype is A.prototype, which contains function f
// by inheritance, b has access to both g and f

[see JS: Class]

“extends” Syntax

class B extends A {body}

The A on the right side must be a constructor (or null). Typically, it should be a function object defined by keyword class or function, or builtin constructor object such as Array, Date, etc.

[see JavaScript Object Reference]

What Does “extends” Do Exactly?

When you have

class B extends A {body}

Basically the following happens:

  1. Run class B {body}.
  2. Make the parent of B to be A.
  3. Make the parent of B.prototype to be A.prototype.
// create a class
class A {}

// extend it
class B extends A {}

// parent of B is A
console.log ( Reflect.getPrototypeOf ( B ) === A );

// parent of B.prototype is A.prototype
console.log ( Reflect.getPrototypeOf ( B.prototype ) === A.prototype );

Extend a Class with Constructor

Default constructor for base class is constructor() {}

Default constructor for derived class is constructor(…) { super(…); }

When you extend a class, and if you create a new constructor, you must call the base class constructor first, by the syntax super(…).

Keyword “super”

JS: Keyword “super”

JS Constructor/Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog