Classes in JS
What a class is
A class is syntactic sugar over a constructor function and prototypes.
That is, "under the hood" classes work the same way JavaScript always has, but they look and read much more simply.
A simple class example
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHi() {
console.log(`Hi, my name is ${this.name}`);
}
}
const user1 = new User('Alex', 25);
user1.sayHi(); // Hi, my name is Alexclass declares a class
constructor() is a special method called on new User()
this is a reference to the object being created
Methods in a class automatically end up on prototype
What this looks like under the hood
This code:
class User {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}is equivalent to the old ES5 code:
function User(name) {
this.name = name;
}
User.prototype.sayHi = function() {
console.log(this.name);
};Key features of classes
| Feature | Description |
|---|---|
| constructor() | A method run when an object is created (new) |
| class methods | Added to prototype and available to every instance |
| extends | Inheritance from another class |
| super() | Calls the parent's constructor |
| static | Static methods/properties, belong to the class itself |
private fields (#) | Fields not accessible outside the class |
| getters/setters | Let you control how properties are read and written |
An example with inheritance
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound.`);
}
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // calls the parent's constructor
this.breed = breed;
}
speak() {
console.log(`${this.name} barks!`);
}
}
const rex = new Dog('Rex', 'shepherd');
rex.speak(); // Rex barks!extends links the class prototypes
super() calls the parent's constructor
You can override methods (as in classic OOP)
Static methods and properties
class MathUtil {
static add(a, b) {
return a + b;
}
}
console.log(MathUtil.add(2, 3)); // 5static means the method belongs to the class itself, not its instances.
Private fields and methods (#)
Added in ES2022:
class Account {
#balance = 0; // private field
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
const acc = new Account();
acc.deposit(100);
console.log(acc.getBalance()); // 100
console.log(acc.#balance); // Error: private propertyFields with # are accessible only inside the class.
Getters and setters
class User {
constructor(name) {
this._name = name;
}
get name() {
return this._name.toUpperCase();
}
set name(value) {
this._name = value.trim();
}
}
const user = new User(' tim ');
console.log(user.name); // TIM
user.name = ' Alex ';
console.log(user.name); // ALEXThese let you control how properties are read and changed.
Class expressions
A class can be declared as an expression:
const User = class {
sayHi() {
console.log('Hi!');
}
};
new User().sayHi(); // Hi!Or even given a name that is only visible inside the definition:
const User = class MyUser {
getClassName() {
return MyUser.name;
}
};Difference between classes and constructor functions
| Criterion | Constructor function | Class |
|---|---|---|
| Syntax | Old, verbose | Modern, declarative |
new required | Yes | Yes |
| Methods | Via prototype | Inside the class body |
Behavior of this | Can be unpredictable | Clear, standard |
Support for extends | Manual | Built in |
| Private fields | None | Available (via #) |
Important to remember
- Classes are not hoisted, like functions are.
const user = new User(); // ReferenceError
class User {}- Inside a class, all methods are non-enumerable, unlike regular properties on prototypes.
- Classes are syntactic sugar over prototypes, not a new inheritance model.
Short summary
| Concept | What it does |
|---|---|
class | Declares a class |
constructor | The method called on new |
extends | Inheritance |
super() | Calls the parent's constructor |
static | Methods of the class, not the instance |
#field | A private property |
get / set | Controls access to properties |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.