OOP & Classes in JavaScript - Exercise 1

A class is a blueprint for creating objects with shared data and behavior.

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

Use the new keyword to create an object from a class.

const firstUser = new User('Ada');
console.log(firstUser.name);

The constructor runs when an instance is created and initializes its properties.

class Product {
  constructor(name, price) {
    this.name = name;
    this.price = price;
  }
}

Write a method inside the class body without the function keyword.

class Counter {
  constructor() {
    this.value = 0;
  }

  increment() {
    this.value += 1;
  }
}

Use dot notation or bracket notation on the instance.

const book = { title: 'JavaScript' };
console.log(book.title);
console.log(book['title']);

Assign a fallback value in the constructor, often with the nullish coalescing operator.

class Task {
  constructor(title, status) {
    this.title = title;
    this.status = status ?? 'todo';
  }
}

It checks whether an object was created from a class or appears in its prototype chain.

const task = new Task('Review code');
console.log(task instanceof Task); // true

A class centralizes shared setup and behavior, making repeated objects consistent and easier to maintain.

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