Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Classes (ES6) in JavaScript

Learn ES6 classes in JavaScript: constructor, methods, extends and super, static methods, and getters and setters, with a simple explanation and output.

IntermediateJavaScript Object ProgramsExample 2 of 2
classes-es6.js
1// Class declaration
2class Person {
3 constructor(name, age) {
4 this.name = name;
5 this.age = age;
6 }
7
8 greet() {
9 return `Hello, I'm ${this.name}`;
10 }
11
12 getAge() {
13 return this.age;
14 }
15}
16
17let person1 = new Person("Alice", 25);
18console.log(person1.greet());
19console.log("Age:", person1.getAge());
20
21// Class with inheritance
22class Student extends Person {
23 constructor(name, age, grade) {
24 super(name, age); // Call parent constructor
25 this.grade = grade;
26 }
27
28 study() {
29 return `${this.name} is studying`;
30 }
31
32 // Override parent method
33 greet() {
34 return `Hi, I'm ${this.name}, a student`;
35 }
36}
37
38let student1 = new Student("Bob", 20, "A");
39console.log("\nStudent:");
40console.log(student1.greet());
41console.log(student1.study());
42console.log("Grade:", student1.grade);
43
44// Static methods
45class MathUtils {
46 static add(a, b) {
47 return a + b;
48 }
49
50 static multiply(a, b) {
51 return a * b;
52 }
53}
54
55console.log("\nStatic methods:");
56console.log("Add:", MathUtils.add(5, 3));
57console.log("Multiply:", MathUtils.multiply(5, 3));
58
59// Getters and Setters
60class Circle {
61 constructor(radius) {
62 this._radius = radius;
63 }
64
65 get radius() {
66 return this._radius;
67 }
68
69 set radius(value) {
70 if (value > 0) {
71 this._radius = value;
72 } else {
73 throw new Error("Radius must be positive");
74 }
75 }
76
77 get area() {
78 return Math.PI * this._radius ** 2;
79 }
80}
81
82let circle = new Circle(5);
83console.log("\nCircle:");
84console.log("Radius:", circle.radius);
85console.log("Area:", circle.area.toFixed(2));
86circle.radius = 10;
87console.log("New radius:", circle.radius);
88console.log("New area:", circle.area.toFixed(2));

Sample Output

Hello, I'm Alice
Age: 25

Student:
Hi, I'm Bob, a student
Bob is studying
Grade: A

Static methods:
Add: 8
Multiply: 15

Circle:
Radius: 5
Area: 78.54
New radius: 10
New area: 314.16

In this one

  • How to define a class with a constructor
  • How extends and super create a child class
  • What static methods are for
  • How getters and setters guard a value

How it works

  1. 1

    new Person creates Alice and calls greet and getAge.

  2. 2

    new Student calls super, then sets grade.

  3. 3

    student1.greet() uses the overridden method.

  4. 4

    MathUtils.add and multiply are called on the class.

  5. 5

    Circle reads radius and area, then sets radius to 10.

Edge cases

Forgetting super()

Using this before super() in Student throws a ReferenceError.

Call super(...) first in any child constructor.

Invalid setter value

circle.radius = -2 throws "Radius must be positive".

The setter protects the value. Wrap the assignment in try/catch if input is untrusted.

Calling without new

Person("Alice", 25) throws a TypeError.

Classes must be created with new.

What's going on

A class is a blueprint for creating objects. Instead of writing the same properties and methods for every student, you write them once in a class and create objects from it. Under the hood, classes are syntactic sugar over prototypes. That means they are a nicer way to write what JavaScript already did with prototypes.

The Person class has a constructor. The constructor runs when you write new Person("Alice", 25). It stores name and age on this, the new object. greet and getAge are methods shared by every Person.

Always use new. Without it, calling a class throws a TypeError. With old constructor functions in strict mode, forgetting new left this as undefined and caused confusing errors.

Student extends Person. extends means Student gets everything Person has. Its constructor must call super(name, age) before using this. super runs the parent constructor. If you skip super, the derived constructor throws a ReferenceError. Student also overrides greet, so a student greets differently, and adds a new method, study.

MathUtils has static methods. Static methods belong to the class itself, not to objects. You call MathUtils.add(5, 3) without new.

Circle uses a getter and setter. get radius lets you read circle.radius like a property. set radius runs when you assign a value. It rejects zero or negative numbers by throwing an error. get area calculates the area every time you read it. The underscore in _radius is a naming habit that says "treat this as internal".

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What must a child constructor call before using this?

Pick an answer to check it.

Question 2

How do you call a static method add on MathUtils?

Pick an answer to check it.

Questions people ask

Are classes different from constructor functions?

They create the same kind of objects with prototypes, but the syntax is clearer and they require new.

Is _radius private?

No. It is just a naming habit. Real private fields use #radius.

When should I use static methods?

For helpers that do not need any object data, like MathUtils.add.