Menu
Coddy logo textTech

The extends Keyword

Part of the Object Oriented Programming section of Coddy's JavaScript journey. Lesson 26 of 56.

The extends keyword in JavaScript is used to create a child class that inherits properties and methods from a parent class.

Let's first create a parent class:

class Animal {
  constructor(name) {
    this.name = name;
  }
  
  speak() {
    return `${this.name} makes a noise.`;
  }
}

Now, let's create a child class that extends the parent class:

class Dog extends Animal {
  // The Dog class inherits from Animal
}

This simple code means that the Dog class now inherits all the properties and methods from the Animal class.

Create a dog instance:

const dog = new Dog('Rex');

Call a method inherited from the parent:

console.log(dog.speak()); // Outputs: "Rex makes a noise."

The extends keyword creates an inheritance relationship where the child class (Dog) can access and use all the functionality defined in the parent class (Animal).

challenge icon

Challenge

Create a Student class that extends the Person class using the extends keyword and export it.

Try it yourself

import { Student } from './classes.js';

// Test code - don't modify
const student = new Student("Emma");
console.log(student.greet());  // Should output "Hello, I'm Emma"
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming

Practice on your own: Online JavaScript compiler