🏗️

How to Use Classes in JavaScript

JavaScriptIntermediate

Object-oriented programming with ES6 classes.

Code Example

JavaScript
// Basic class
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  
  greet() {
    return `Hello, I'm ${this.name}`;
  }
}

const person = new Person("Alice", 30);
console.log(person.greet());

// Inheritance
class Employee extends Person {
  constructor(name, age, job) {
    super(name, age);
    this.job = job;
  }
  
  work() {
    return `${this.name} is working as ${this.job}`;
  }
}

const employee = new Employee("Bob", 25, "Developer");
console.log(employee.greet());
console.log(employee.work());

// Static methods
class MathHelper {
  static square(x) {
    return x * x;
  }
  
  static cube(x) {
    return x * x * x;
  }
}

console.log(MathHelper.square(5));
console.log(MathHelper.cube(3));

// Getters and setters
class Circle {
  constructor(radius) {
    this._radius = radius;
  }
  
  get area() {
    return Math.PI * this._radius ** 2;
  }
  
  set radius(value) {
    if (value < 0) throw new Error("Radius cannot be negative");
    this._radius = value;
  }
}

const circle = new Circle(5);
console.log(circle.area);
circle.radius = 10;

// Private fields (modern JS)
class BankAccount {
  #balance = 0;
  
  deposit(amount) {
    this.#balance += amount;
  }
  
  get balance() {
    return this.#balance;
  }
}

const account = new BankAccount();
account.deposit(100);
console.log(account.balance);

Explanation

Classes use constructor, extends for inheritance, super() to call parent. Static methods belong to class. Getters/setters control access. # for private fields.

Related Tutorials