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.
1// Class declaration2class Person {3 constructor(name, age) {4 this.name = name;5 this.age = age;6 }78 greet() {9 return `Hello, I'm ${this.name}`;10 }1112 getAge() {13 return this.age;14 }15}1617let person1 = new Person("Alice", 25);18console.log(person1.greet());19console.log("Age:", person1.getAge());2021// Class with inheritance22class Student extends Person {23 constructor(name, age, grade) {24 super(name, age); // Call parent constructor25 this.grade = grade;26 }2728 study() {29 return `${this.name} is studying`;30 }3132 // Override parent method33 greet() {34 return `Hi, I'm ${this.name}, a student`;35 }36}3738let student1 = new Student("Bob", 20, "A");39console.log("\nStudent:");40console.log(student1.greet());41console.log(student1.study());42console.log("Grade:", student1.grade);4344// Static methods45class MathUtils {46 static add(a, b) {47 return a + b;48 }4950 static multiply(a, b) {51 return a * b;52 }53}5455console.log("\nStatic methods:");56console.log("Add:", MathUtils.add(5, 3));57console.log("Multiply:", MathUtils.multiply(5, 3));5859// Getters and Setters60class Circle {61 constructor(radius) {62 this._radius = radius;63 }6465 get radius() {66 return this._radius;67 }6869 set radius(value) {70 if (value > 0) {71 this._radius = value;72 } else {73 throw new Error("Radius must be positive");74 }75 }7677 get area() {78 return Math.PI * this._radius ** 2;79 }80}8182let 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
new Person creates Alice and calls greet and getAge.
- 2
new Student calls super, then sets grade.
- 3
student1.greet() uses the overridden method.
- 4
MathUtils.add and multiply are called on the class.
- 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.