<img alt="javascript classes" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/javascript-classes.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

JavaScript is a multi-paradigm language that allows you to write programs that follow functional, object-oriented, and imperative programming styles.

To support object-oriented patterns, JavaScript has classes. Because understanding them is crucial, this article is a guide on what JavaScript classes are and how to use them.

What are Classes in JavaScript?

<img alt="YouTube video" data-pin-nopin="true" data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/maxresdefault.jpg650d7fce627df.jpg" height="720" nopin="nopin" src="data:image/svg xml,” width=”1280″>

In object-oriented programming, we model systems as groups of objects that interact with each other. To function, objects store data in properties and perform actions defined as their methods. A class defines what properties and methods are carried by objects of the same type. Therefore, classes are blueprints for objects.

Terminologies Used in Classes

To ensure we are on the same page, here is a description of classes with key terms we will use in this article. If you are already familiar with object-oriented programming, you may skip to the next section.

❇️ A class is a blueprint for an object. It provides a template from which objects of that type can be made. Creating an object from the template provided by the class is called instantiation.

❇️ A class member is anything that belongs to the class. There are two kinds of class members – methods and properties.

❇️ A property is a class member whose primary purpose is to store values. These could be simple values such as numbers and strings. They could also be complex objects and arrays.

❇️ Some properties are only accessible inside the class and are aptly named private properties. Some are accessible both within and outside the class. Such properties are called public properties.

❇️ A method is a function defined inside a class. Therefore, it belongs to the class and has access to public and private properties. Like properties, we also have public methods and private methods.

❇️ Some methods exist to provide an interface for code outside the class to interact with properties inside the class. There are two groups of methods that do this: getters and setters. Getters get values of class properties, while setters set values of class properties.

❇️ Some members are static. This means they are only accessible on the class and cannot be accessed on class instances.

In contrast, some class members are not static, meaning they can only be accessed on class instances. You have to instantiate the class before you can access a non-static member.

When you instantiate a class, a special method is called to set up properties for the instance. This method is called the constructor function.

Instantiating a Class Explained

We use the new keyword and the class name to instantiate a class in JavaScript. For example, let us instantiate the Array class.

const myArr = new Array()

Creating Classes in JavaScript

This section will discuss creating a class that implements all the concepts we covered in the Terminology Section. We will do this in a series of examples, where each example builds on the previous ones.

Declaring an Empty Class

To declare a class in JavaScript, we use the class keyword and give the class a name. Next, we define the body of the class. The body is enclosed in curly braces and holds all the class members.

Here’s an example class declaration with an empty body:

class Dog {

}

Now, you can instantiate the class as follows and print it out.

const pet = new Dog;
console.log(pet);
<img alt="output- new class" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-13-24.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Creating Public Properties

Public Properties are defined with an identifier and an optional value.

class Dog {
    name = "Roy";
    age;
}

Here, we have defined the name with a string value and the age with no value.

const pet = new Dog();

console.log(pet.name);
console.log(pet.age);
<img alt="output- class" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-16-39.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Defining Public Methods

We can add methods to our class inside its body. We define a method in the same way we would define a function. However, we omit the function keyword.

class Dog {
    name = "Roy";
    age;

    walk () {
        console.log("Walking");
    }
}

In the example above, we defined the walk method. Every instance of the Animal class will have that method.

const pet = new Dog();
pet.walk();
<img alt="output-animal class" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-24-01.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Accessing Properties from Methods

In JavaScript, we generally access properties on an object using the dot operator. For example, if we had an object named person and wanted to access the name property, we would do that as follows.

person.name

However, if we want to access a property from within the object, we use the this keyword instead of the object name. Here’s an example:

this.name

The this keyword references the object. So, if we wanted to access class properties from within class methods, we would use this. syntax.

Creating Private Properties

Suppose we wanted the name and age properties we defined earlier to be private. We would redefine the class as follows:

class Dog {
    #name = "Roy";
    #age;

    walk () {
        console.log("Walking");
    }
}

As you can see, private properties are specified using pound signs. If you tried to access them, you would run into errors.

const dog = new Dog();

dog.#name
<img alt="Creating Private Properties" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-26-10.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Creating Getter and Setter Methods

Now, the name and age properties of the class are private. Therefore, they can only be accessed by methods inside the class.

If we want to enable code outside the class to access these properties, we define getters and setters. Let us do that for the name property.

class Dog {
    #name = "Roy";
    #age;

    get name () {
        return this.#name;
    }

    set name (value) {
        this.#name = value;
    }

    walk () {
        console.log("Walking");
    }
}

With the class defined above, you can set the name and display it using the code below:

const pet = new Dog();

// Setting the name
pet.name = "Rex";

// Getting the name
console.log(pet.name);
<img alt="Creating Getter and Setter Methods" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-33-05.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Creating Private Methods

Like private properties, private methods are prefixed with the pound sign. Therefore, declaring a private method would look like this:

class Dog {
    #name = "Roy";
    #age;

    get name () {
        return this.#name;
    }

    set name (value) {
        this.#name = value;
    }

    #increaseAge() {
        this.#age   ;
    }

    #decreaseAge () {
        this.#age --;
    }

    walk () {
        console.log("Walking");
    }
}

If you tried to access these methods from outside the class, it would not work.

const pet = new Dog();
pet.#increaseAge();
<img alt="Creating Private Methods" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-37-21.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Creating a Constructor Method

You can also define the constructor method. This method will automatically be called whenever you instantiate a new class. The constructor method can be used to initialize properties. In this example, we will initialize the age and name to whatever arguments the user provides during instantiation.

class Dog {
    #name;
    #age;

    constructor (name = "Dog", age = 0) {
        this.#name = name;
        this.#age = age;
    }

    get name () {
        return this.#name;
    }

    set name (value) {
        this.#name = value;
    }

    #increaseAge() {
        this.#age   ;
    }

    #decreaseAge () {
        this.#age --;
    }

    walk () {
        console.log("Walking");
    }
}

When we instantiate our class, we can supply a name and age.

const pet = new Dog('Roy', 3);
console.log(pet.name);
<img alt="Creating a Constructor Method" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-47-25.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Creating Static Properties and Methods

As mentioned, static members can be accessed without instantiating the class first. In the example below, we will create a static property and method.

class Dog {
    #name;
    #age;
    static genus = "Canis";

    constructor (name = "Dog", age = 0) {
        this.#name = name;
        this.#age = age;
    }

    static bark() {
        console.log("Woof");
    }

    get name () {
        return this.#name;
    }

    set name (value) {
        this.#name = value;
    }

    #increaseAge() {
        this.#age   ;
    }

    #decreaseAge () {
        this.#age --;
    }

    walk () {
        console.log("Walking");
    }
}

Now, you can access the static property and method without instantiation.

console.log(Dog.genus);
Dog.bark();
<img alt="Creating Static Properties and Methods" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-04-48-44.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Inheritance

Classes can inherit properties from other classes. A class that inherits members from another class is called a superclass, while the class it inherits members from is the base class or subclass.

To create a superclass in JavaScript, we use the extends keyword. Here’s an example where we inherit from the Dog class.

class Rottweiler extends Dog {
    constructor (name, age) {
        super(name, age);
        this.breed = 'rottweiler';
    }
}

As you can see, the class is largely the same as before. However, inside the constructor, we called the super function. The super keyword references the base class’ constructor. Therefore, we called the base class’s constructor inside our superclass, passing in name and age.

const myPet = new Rottweiler();
console.log(myPet);
<img alt="Inheritance" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Screenshot-from-2023-09-14-05-00-45.png/w=786" data- decoding="async" height="533" src="data:image/svg xml,” width=”786″>

Conclusion

In this article, we covered classes. We covered what they are, the members they can hold, and the different classifications for the members. Then, we illustrated all this with examples.

Next, you may want to read object-oriented programming interview questions.