Topic Overview

Welcome back, JavaScript enthusiast! We're diving back into JavaScript classes, focusing on constructors and class methods. Picture building a robot: Constructors are the initial settings, and class methods are the commands that enable it to perform actions. Are you ready for a refresher? Let's get started!

Revisiting JavaScript Classes

A JavaScript class serves as a blueprint for creating objects. Here's a basic class, Robot:

class Robot {
    // Class definition
}

const robotInstance = new Robot();

As of now, this Robot class is like an empty shell. It exists but doesn't know how to do anything. To make it functional, attributes and methods are needed.

Deep Dive into Constructors

A constructor is a special method that initializes an object when it is created. In JavaScript, this method is always named constructor and is called automatically during object creation. It sets up the initial states of the new object.

If you do not define a constructor method in your class, JavaScript will provide an empty constructor method automatically.

Here, we upgrade the Robot class with a constructor:

class Robot {
    constructor(name, color) {
        this.name = name;
        this.color = color;
    }
}

const robotInstance = new Robot("Robbie", "red");  // Robbie, a red robot, is born!

In this case, the constructor method gets automatically called when we create a new Robot instance, set with name and color attributes. It's always good practice to use constructors like constructor to ensure each instance starts with the correct initial values.

Multiple Constructors with Default Parameters

Having one constructor is great, but what if we want more flexibility in setting up our robots? That's where default parameters come into play and give us something similar to multiple constructors.

Here's a default color for our robots:

class Robot {
    constructor(name, color = 'grey') {
        this.name = name;
        this.color = color;
    }
}

const robotInstance = new Robot("Robbie", "red");  // Red Robbie
const robotInstance2 = new Robot("Bobby");  // Grey Bobby, no color provided

With default parameters, color becomes optional. When we don't specify it, the robot is 'grey' by default.

Class Methods
Updating and Retrieving Parameters with Class Methods
Lesson Summary

Great job! You've refreshed and deepened your understanding of JavaScript classes, constructors, and class methods, and learned how to mimic multiple constructors. Additionally, you saw how to add methods that can update and retrieve class attributes. Now, you can breathe more life into your JavaScript classes, making them more versatile and powerful. Next, we'll move on to hands-on tasks where you'll apply these concepts to more complex scenarios. Keep up the good work!

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