Classes: Beautiful OOP

A class in JavaScript is a blueprint for creating objects with shared structure and behavior.

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

  sayHi() {
    alert('Hello, ' + this.name); // class method
  }
}

let user = new User('Alice');
user.sayHi(); // Hello, Alice

Key Things to Know

  1. Methods inside a class are NOT separated by commas.
  2. A class CANNOT be called without new — you'll get a TypeError.
  3. All code inside a class body always runs in strict mode (use strict) automatically.

Classes Are Not Just Syntax Sugar

Unlike regular constructor functions, class declarations are NOT hoisted. You cannot use a class before it's defined:

const obj = new MyClass(); // ReferenceError!
class MyClass {}
Note

Under the hood, classes use the exact same prototype mechanism you learned in Module 9. A class is essentially a cleaner way to write a constructor function + prototype methods.