How to Create a Class in JavaScript

Many tend to write JavaScript as a series of statements and functions. It does not have to be that way. JavaScript allows you to create classes that can be instantiated and perform actions, much like how you can in other languages. In this post we will look at how we can use classes in JavaScript to organize our code a little better. JavaScript quickly turns into thousands of lines of spaghetti code that is difficult to follow, so being able to organize it better can add a lot of value.

A class in JavaScript looks a lot like a class in for example C#. If consists of a “class” keyword followed by a class name. It has a series of properties and methods, as well as a constructor. You can inherit from a class, which is quite convenient if you have many things that share the same property.

A simple class definition could look like the following.

class Button{
    buttonName;
    buttonColor;
    buttonText;
    buttonId;

    constructor(name, color, text, id){
        this.buttonName = name;
        this.buttonColor = color;
        this.buttonText = text;
        this.buttonId = id;
    }

    addOnClickEventListener(){
        $("#" + this.buttonId).click(function(){
            // Do something
        });
    }
}

You can copy the class above into the console to try it out. You can initialize it with the following code:

var test = new Button("test", "blue", "teteefef", 1);

A common place where you quickly drown in JavaScript code is if you are writing validation code. You have input fields and you want to validate them.

Now we can use inheritance in JavaScript also. Let us say we had many buttons on our website. They all share certain functionality, such as name and text, but some should have special behaviors. We can create special button classes and inherit from our regular button class.

class PurchaseButton extends Button {
    constructor(name, color, text, id){
        super(name, color, text, id);
    }

    // Add special behavior here
}

I hope you are able to find use cases for this in your own code, as you can often save hundreds of lines of codes by using classes in JavaScript. I am sure that you are able to follow the code that you have written, but it can be very difficult for someone who comes in later to understand everything. Also, if you want to make changes it is a lot easier to change things when there is less code.

If you want more JS knowledge then have a look at this post which explains how to find the average of an array using JavaScript.