Labs ICT
โญ Pro Login

Classes

1 min read | JavaScript Tutorial
โญ

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

Class Syntax

ES6 introduced the class keyword as syntactic sugar over prototype-based inheritance.

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

  introduce() {
    return "Hi, I'm " + this.name + " and I'm " + this.age;
  }
}

const alice = new Person("Alice", 30);
console.log(alice.introduce());

Getters & Setters

Use get and set to define computed properties with accessor syntax.

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  get area() {
    return this.width * this.height;
  }

  set dimensions({ w, h }) {
    this.width = w;
    this.height = h;
  }
}

const rect = new Rectangle(5, 10);
console.log(rect.area);
rect.dimensions = { w: 3, h: 7 };
console.log(rect.area);

Static Methods

Static methods belong to the class itself, not instances. Use the static keyword.

class MathHelper {
  static add(a, b) {
    return a + b;
  }

  static multiply(a, b) {
    return a * b;
  }
}

console.log(MathHelper.add(5, 3));
console.log(MathHelper.multiply(4, 2));

๐Ÿงช Quick Quiz

What keyword defines a class in JavaScript?