Last Updated : 29 Jul, 2025
JavaScript classes (introduced in ES6) provide a structured way to create objects with shared properties and methods. They support inheritance, encapsulation, and modularity, making it easier to write object-oriented code.
Javascript ClassSyntax
class ClassName {
constructor() {
// Initialize properties here
}
// Define methods here
methodName() {
// Method code
}
}
A basic class that defines properties and methods. This example shows how to create an object with a constructor and method.
JavaScript
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
g() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
let p1 = new Person("Pranjal", 20);
p1.g();
Hello, my name is Pranjal and I am 20 years old.
The constructor is used to initialize the properties of the object when an instance is created.
JavaScript
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
d() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
}
let my = new Car("Toyota", "Corolla", 2021);
my.d();
2021 Toyota Corolla
Inheritance allows one class to extend another, inheriting its properties and methods while adding or overriding functionality.
JavaScript
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
di() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
}
class ElectricCar extends Car {
constructor(make, model, year, batteryLife) {
super(make, model, year);
this.batteryLife = batteryLife;
}
d() {
console.log(`Battery life: ${this.batteryLife} hours`);
}
}
let tesla = new ElectricCar("Tesla", "Model S", 2022, 24);
tesla.di()
tesla.d();
2022 Tesla Model S Battery life: 24 hours
Using classes to create multiple objects with the same structure but different data.
JavaScript
class Car {
constructor(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
d() {
console.log(`${this.year} ${this.make} ${this.model}`);
}
}
let c1 = new Car("Toyota", "Corolla", 2021);
let c2 = new Car("Honda", "Civic", 2020);
c1.d();
c2.d();
2021 Toyota Corolla 2020 Honda Civic
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4