A class in JavaScript is a type of function that uses the keyword class rather than function and a special constructor method that gets called when a new instance of the class is created. The constructor is important because it provides the properties of the new instance to the class.

For better understanding, think of classes as some sort of blueprint (skeleton) that can be reused to create different instances each with unique properties and methods. This is important especially when creating software as it promotes code organization, reusability, and maintainability.

Let's see how to create classes in JavaScript.

How to create classes in JavaScript

To create a class, start by using the reserved class keyword followed by a name for your class. (You could call the class anything as long as it makes sense to whatever you are doing). Finish off by using an opening and closing curly brace. Here is an example.

class Animal {
    
}
Note: The first letter of the name of the class must be in Upper case.

The example above shows a valid class and we can start creating different instances of the class. Let's see how to do this.

Creating a class instance

To create a new instance of the class, we are going to use the new keyword followed by the name of the class and finish with parenthesis. Here is an example.

const cat = new Animal() //Create a new instance of Animal with the name cat.

In this example, we have created an Animal instance with the name of "cat" using the Animal blueprint. The new keyword tells JavaScript this is a new instance of Animal. The Parenthesis at the end shows that we are calling the Animal class as a function.

We can then pass arguments inside the parenthesis which are unique to this class instance but before that, let's add another instance so that you get the idea completely.

const dog = new Animal() //Create a new instance of Animal with the name Dog using the new keyword.

Instead of "cat", this time round we have created a new instance of Animal with the name dog.

As you know, "dog" and "cat" have different properties, to put this into consideration, we are going to add those unique properties inside the parenthesis.

Here is all the code we have so far.

class Animal {
    
}

const cat = new Animal() //Create a new instance of Animal with the name cat.
const dog = new Animal() //Create a new instance of Animal with the name dog.

Adding Arguments to a class

Let's give properties to our animals. We are going to give names to the animals and show the sounds they make.

I will call my dog "dog" and cat "cat" that way it is easy to follow. As we know, a cat meows, and a dog barks. Let's see this in action.

const cat = new Animal("cat", "meow") 
const dog = new Animal("dog", "barks")

console.log(cat);

We now have our Animal instances with their unique properties. We can now try to print to the console and see what we have.

Output:

As you can see from the Output, we only get the class name with an empty object. This empty object is what will hold the properties unique to the class instance.

So why does it not show the properties inside the object?

If you remember from the description of a class at the top, I said a class also has a special constructor method that provides the properties of the new instance to the class. Let's see how to create the constructor function.

Creating the constructor function

The constructor function is the function that gets called when a new instance of the class is created. This function takes in the parameters set from the class instance.

To create the constructor, inside the class function, use the constructor keyword followed by parenthesis then curly braces as shown below. Inside the parenthesis is where you pass the arguments then inside the curly braces, this is where we have the function body.

class Animal {
    constructor() {
        
    }
}

Now that we have a constructor function in place, let's pass in the arguments and use those arguments inside the body.

class Animal {
    constructor(name, sound) {
        this.name = name;
        this.sound = sound;
    }
}

From this example, we have passed the arguments inside the constructor, then used those arguments in the body to customize the individual instance of the Animal. To achieve this, we are using this keyword to set this Animal's particular name and sound. The = symbol tells JavaScript to set the name to the name provided in the arguments. And by doing that, we should now see the properties of the animals when we print to the screen.

Output:

As you can see, we now have the properties of the animals inside the object. With this done, we can now create as many instances of Animal as we like. We can make one for "Cow", "Hen" etc.

We now know how to create classes with unique elements, let's now see how we can create classes that have reusable code using methods.

Creating methods in a class

Similar to a constructor method, we can create our own methods. The difference will be these methods will only run when they are called and you can give them any name. Let's see how to create a method.

In this example, we call the method makeSound. Just like we created the constructor function, do the same for this one. Below the constructor method, create a new method by giving it a name followed by parenthesis then curly braces. We want this method to print to screen "this Animal makes the sound specified in the argument". This is how your code should look.

class Animal {
    constructor(name, sound) {
        this.name = name;
        this.sound = sound;
    }
    
    makeSound() {
        return `${this.name} says ${this.sound}`    
    }
}

const cat = new Animal("cat", "meow") 
const dog = new Animal("dog", "barks")

In this method, we don't need any arguments because we are going to use the ones from the constructor function.

To log into the console, we need to call the method as shown below.

console.log(cat.makeSound());
console.log(dog.makeSound());

The custom methods are available inside the class Instance. That is why I use the cat instance followed by the method name.

Output:

As you can see, We get the name and the sound the animal makes using reusable code.

That is it for this one. If you have any questions, drop them in the comments section.

Conclusion

In this article, we have created a basic class, made an instance of the class, and given it parameters that can be accessed inside the constructor function. We have also created our method that is similar to the constructor method only that this method must be called for it to work.

If you found the article helpful, be sure to subscribe and share the article with interested parties

Thanks, for reading : )

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.