Class in JavaScript

Manish Sharma
2 min readApr 22, 2023

--

Classes in JavaScript are an essential aspect of object-oriented programming (OOP). OOP is a paradigm that helps organize complex code by breaking it down into smaller, more manageable pieces. It allows for code reuse, which leads to better maintainability and scalability.

In this blog post, we’ll discuss classes in JavaScript with an example.

Understanding Classes in JavaScript

Classes are a blueprint for creating objects. They provide a way to define objects with similar properties and methods. In JavaScript, classes are implemented using the class keyword.

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}

greet() {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old`);
}
}

const person1 = new Person("John Doe", 25);
person1.greet(); // output: "Hello, my name is John Doe and I'm 25 years old"

In this example, we’ve defined a Person class that has a name and age property, as well as a greet() method that logs a greeting message to the console. We then create an instance of this class using the new keyword and call the greet() method on it.

Using Classes in JavaScript

To better understand how classes work in JavaScript, let’s take an example

Consider a Person class that has a name, age, and gender property, as well as a greet() method that greets the person in an Indian style. Here's how we can implement this class in JavaScript:

class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

greet() {
if (this.gender === "Male") {
console.log(`Namaste, main ${this.name} hoon aur main ${this.age} saal ka hoon`);
} else if (this.gender === "Female") {
console.log(`Namaste, main ${this.name} hoon aur main ${this.age} saal ki hoon`);
} else {
console.log(`Namaste, main ${this.name} hoon aur main ${this.age} saal ka hoon`);
}
}
}
const person1 = new Person("Rahul", 30, "Male");
person1.greet(); // output: "Namaste, main Rahul hoon aur main 30 saal ka hoon"
const person2 = new Person("Priya", 25, "Female");
person2.greet(); // output: "Namaste, main Priya hoon aur main 25 saal ki hoon"
const person3 = new Person("Ali", 40);
person3.greet(); // output: "Namaste, main Ali hoon aur main 40 saal ka hoon"

In this example, we’ve defined a Person class that has a name, age, and gender property, as well as a greet() method that greets the person in an Indian style using the Namaste greeting.

We create three instances of this class with different properties and call the greet() method on each instance, which logs a greeting message to the console.

--

--

Manish Sharma

HackerRank Certified Professional | System Design, System Architecture and Programming Concepts (manish.official@outlook.com) https://www.systemdesign.live