Topic Overview

Hello, Explorer! Today, we're unveiling a core concept of Object-Oriented Programming (OOP): JavaScript classes. These classes act as blueprints, allowing us to generate objects — instances of these blueprints — each carrying unique properties and behaviors. This lesson has one aim: to understand what classes are, how to create them, and their purpose within your JavaScript code.

Understanding Classes in JavaScript

Think of a JavaScript class as a construction blueprint. By following the blueprint, we can create specifically structured objects, each filled with different values.

class Fruit {
}

Here, Fruit is our blueprint or class. This blueprint then enables us to generate a variety of fruit objects with specialized attributes, much like constructing a building.

Creating an Instance of a Class

Creating an instance of a class, essentially bringing an object to life from this blueprint, uses the new keyword:

let apple = new Fruit();

In this example, apple is a specific instance or object of our Fruit class, much like a single building constructed from a shared blueprint.

Incorporating a Simple Function (Method) Inside a Class

To bestow behavior upon our class, we incorporate methods — these are functions that belong to a class. Let's add a straightforward printColor method inside our Fruit class:

class Fruit {
  printColor() {
    console.log('Red'); // This will print out 'Red' when called
  }

  printMessage(name) {
    console.log(`Do you want a fruit, ${name}?`);
  }
}

The printColor method here is a straightforward function that prints Red to the console. Note that we didn't include the function keyword - that's because JavaScript class syntax works this way.

Using an Instance to Call a Method

Now, let's generate an instance of our class and invoke, or call, the printColor method we outlined previously:

let apple = new Fruit();
apple.printColor(); // Outputs: Red
apple.printMessage('John'); // Outputs: Do you want a fruit, John?

We leveraged the printColor method on our apple instance, which resulted in Red being printed on the console.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal