This page looks best with JavaScript enabled

How to Use Javascript Class?

 ·   ·  ☕ 2 min read

Class in Javascript is syntactic sugar on top of prototypes. Class makes it easier to structure our code, and to read and maintain it.

Let’s see a simple class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class QuizTracker {
  constructor() {
    this.right = 0;
    this.wrong = 0;
    this.points = 0;
  }

  addRight() {
    this.right++;
    this.points++;
  }

  addWrong() {
    this.wrong++;
    this.points -= 0.25;
  }

  getPoints() {
    return this.points;
  }
}

Class is the skeleton and provides the framework for an object. Object is an instance of the class and contains the structure supplied by class and the data.

Let us make the above code usable -

1
2
3
4
5
6
7
const quiz1 = new QuizTracker();
quiz1.addRight();
quiz1.addRight();
quiz1.addRight();
quiz1.addWrong();

console.log("Quiz1 Results:", quiz1.getPoints()); // 2.75

First we instantiate quiz1 object. Then we start calling the functions supplied by the class to track quiz points. At the very end, we can get the results and display them.

The same can be done by a function as well, but what if you have multiple quizzes being taken by multiple students.

We can simply do -

1
2
3
4
5
6
7
const quiz2 = new QuizTracker();
quiz2.addWrong();
quiz2.addRight();
quiz2.addWrong();
quiz2.addWrong();

console.log("Quiz2 Results:", quiz2.getPoints()); // 0.25

The data owned by the two objects is different, but the logic is the same.

Classes had made the biggest impact in the way I code in the past, and I am quite excited with the continued improvements to class features in Javascript.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things