JavaScript Classes

JavaScript Classes are templates for creating JavaScript objects. They were introduced in ES6 (2015) and provide a cleaner, more readable syntax for creating objects and dealing with inheritance.

Class Syntax

A class is defined using the class keyword, followed by the class name. The body of a class is enclosed in curly braces {}.

Basic Class Declaration
class Car {
  constructor(brand, year) {
    this.brand = brand;
    this.year = year;
  }
}

const myCar = new Car('Toyota', 2023);
console.log(myCar.brand);
console.log(myCar.year);

The Constructor Method

The constructor() method is a special method for creating and initializing objects. It is called automatically when a new object is created with the new keyword. A class can only have one constructor method.

Constructor with Default Values
class Person {
  constructor(name = 'Unknown', age = 0) {
    this.name = name;
    this.age = age;
  }
}

const p1 = new Person('Alice', 30);
const p2 = new Person();
console.log(p1.name + ' is ' + p1.age);
console.log(p2.name + ' is ' + p2.age);

Class Methods

Class methods are defined inside the class body. You do not need the function keyword when defining methods in a class. Methods are added to the prototype of the class.

Defining and Calling Methods
class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  speak() {
    return this.name + ' says ' + this.sound;
  }

  info() {
    return 'Animal: ' + this.name;
  }
}

const dog = new Animal('Rex', 'Woof');
console.log(dog.speak());
console.log(dog.info());

Creating Instances with new

You create an instance of a class using the new keyword. Each instance has its own copy of the properties defined in the constructor, but shares the methods defined in the class body.

Multiple Instances
class Book {
  constructor(title, author) {
    this.title = title;
    this.author = author;
  }

  describe() {
    return '"' + this.title + '" by ' + this.author;
  }
}

const b1 = new Book('1984', 'George Orwell');
const b2 = new Book('Brave New World', 'Aldous Huxley');
console.log(b1.describe());
console.log(b2.describe());
console.log(b1 === b2);

Class vs Function Constructor

Before ES6, JavaScript used function constructors to create objects. Classes are essentially syntactic sugar over function constructors, but with some important differences.

FeatureClassFunction Constructor
Syntaxclass MyClass {}function MyClass() {}
HoistingNot hoisted (TDZ)Hoisted
Strict modeAlways strictNot by default
Callable without newThrows errorReturns undefined
MethodsOn prototype (non-enumerable)On prototype (enumerable)
Function Constructor vs Class
// Function Constructor (old way)
function PersonFC(name) {
  this.name = name;
}
PersonFC.prototype.greet = function() {
  return 'Hi, I am ' + this.name;
};

// Class (modern way)
class PersonClass {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return 'Hi, I am ' + this.name;
  }
}

const fc = new PersonFC('Bob');
const cl = new PersonClass('Bob');
console.log(fc.greet());
console.log(cl.greet());

Class Declarations vs Expressions

Like functions, classes can be defined using declarations or expressions. Class expressions can be named or unnamed.

Class Expression
// Unnamed class expression
const Rectangle = class {
  constructor(w, h) {
    this.width = w;
    this.height = h;
  }
  area() {
    return this.width * this.height;
  }
};

// Named class expression
const Square = class SquareClass {
  constructor(side) {
    this.side = side;
  }
  area() {
    return this.side * this.side;
  }
};

const r = new Rectangle(5, 3);
const s = new Square(4);
console.log('Rectangle area: ' + r.area());
console.log('Square area: ' + s.area());
console.log(typeof Rectangle);
console.log(typeof Square);
📝 Note: Unlike function declarations, class declarations are not hoisted. You must declare a class before you can use it. Attempting to use a class before it is declared will result in a ReferenceError.
Exercise:
What is the correct syntax to create a class in JavaScript?
Try it YourselfCtrl+Enter to run
Click Run to see the output here.