Static keyword in javascript

static-keyword-in-javascript

Static is a very special keyword in javascript. In another language, it’s used for memory management. Let’s take an example to understand supposed that you have a Student class and students can be related to different courses but their college name is same but is we create variable inside the class every time if we create an instance of that class then it will automatically create that variable but if we use to create static class then it will create only once for all instance of that class.

Static variables and methods related to class so it will not create another copy for the new object of the class. So if we change the static variable all class object automatically change.

Before es6 we don’t have any keyword in Javascript but in the es6 version, we have the static keyword.

We can use static keyword with class variable and class method. Let’s take an example but before to understand this article you need to go through with our Classes and Inheritance article.

How to use static variable


class Student {
    constructor(name) {
        this.name = name;
    }

    static clg = "Xyz";
}


console.log(Student.clg); // Xyz

How to use static method


class Student {
    constructor(name) {
        this.name = name;
    }

    static clg() {

        return "Xyz"
    };
}


console.log(Student.clg()); // Xyz

You May Also Like

About the Author: Pankaj Bisht

1 Comment

Comments are closed.