JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript Classes

14 April 2025 | Category:

In JavaScript, classes provide a cleaner and more structured way to create objects and deal with inheritance. While JavaScript is prototype-based under the hood, classes make it easier to write object-oriented code.


📘 What is a Class?

A class is a blueprint for creating objects. It defines properties (data) and methods (functions) that the objects created from the class will have.


🔧 Declaring a Class

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

  greet() {
    console.log(`Hi, I’m ${this.name} and I’m ${this.age} years old.`);
  }
}

constructor() is a special method that gets called when you create a new object from the class.


🧪 Creating an Object (Instance)

const john = new Person("John", 25);
john.greet(); // Output: Hi, I’m John and I’m 25 years old.

🧬 Inheritance (Extending Classes)

You can create a child class that inherits properties and methods from a parent class using extends.

class Student extends Person {
  constructor(name, age, grade) {
    super(name, age); // Call parent constructor
    this.grade = grade;
  }

  study() {
    console.log(`${this.name} is studying in grade ${this.grade}.`);
  }
}

const dev = new Student("Dev", 20, 12);
dev.greet(); // Inherited method
dev.study(); // New method

📦 Class Methods and Getters

You can add:

  • Regular methods
  • Getters and setters for controlled access to properties
class Product {
  constructor(name, price) {
    this.name = name;
    this._price = price;
  }

  get price() {
    return `$${this._price}`;
  }

  set price(value) {
    if (value < 0) throw new Error("Price can't be negative");
    this._price = value;
  }
}

const item = new Product("Perfume", 120);
console.log(item.price); // $120
item.price = 140;
console.log(item.price); // $140

🛠️ Static Methods

Static methods belong to the class itself, not to any instance:

class MathUtil {
  static square(n) {
    return n * n;
  }
}

console.log(MathUtil.square(5)); // 25

✅ Summary

FeatureDescription
classDefines a blueprint for objects
constructor()Initializes object properties
extendsInherits from another class
super()Calls the constructor of the parent class
staticMethod available on the class, not on instances
get / setCreate custom getters and setters

JavaScript classes are just syntactic sugar over its existing prototype-based inheritance system. They make code more readable and easier to maintain.