JS Tutorial



JS CLASSES


JavaScript Classes ๐Ÿซ

JavaScript classes are templates for creating objects. They encapsulate data with code to work on that data. Classes were introduced in ES6 and are a cleaner way to write constructor functions.

๐Ÿ”ง Class Syntax

class Car {
  constructor(brand) {
    this.brand = brand;
  }

  drive() {
    return `${this.brand} is driving!`;
  }
}

const myCar = new Car("Toyota");
console.log(myCar.drive()); // "Toyota is driving!"

๐Ÿงช Live Example: Class in Action

๐Ÿ“š Class Inheritance

Use extends to inherit from another class:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  speak() {
    return `${this.name} barks.`;
  }
}

const dog = new Dog("Bruno");
console.log(dog.speak()); // "Bruno barks."

โš™๏ธ Using Super()

super() is used to call the parent class constructor:

class Employee {
  constructor(name) {
    this.name = name;
  }
}

class Manager extends Employee {
  constructor(name, dept) {
    super(name); // Call parent constructor
    this.dept = dept;
  }

  getDetails() {
    return `${this.name} manages the ${this.dept} department.`;
  }
}

๐Ÿ“ฆ Class Getters & Setters

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

  get name() {
    return this._name;
  }

  set name(newName) {
    this._name = newName;
  }
}

const p = new Person("Amit");
console.log(p.name);  // Amit
p.name = "Sonia";
console.log(p.name);  // Sonia
Note: Class declarations are not hoisted. Always define your class before using it.

๐ŸŒŸ Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review