Skip to main content

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

javascript
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 Alex

class 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:

javascript
class User { constructor(name) { this.name = name; } sayHi() { console.log(this.name); } }

is equivalent to the old ES5 code:

javascript
function User(name) { this.name = name; } User.prototype.sayHi = function() { console.log(this.name); };

Key features of classes

FeatureDescription
constructor()A method run when an object is created (new)
class methodsAdded to prototype and available to every instance
extendsInheritance from another class
super()Calls the parent's constructor
staticStatic methods/properties, belong to the class itself
private fields (#)Fields not accessible outside the class
getters/settersLet you control how properties are read and written

An example with inheritance

javascript
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

javascript
class MathUtil { static add(a, b) { return a + b; } } console.log(MathUtil.add(2, 3)); // 5

static means the method belongs to the class itself, not its instances.


Private fields and methods (#)

Added in ES2022:

javascript
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 property

Fields with # are accessible only inside the class.


Getters and setters

javascript
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); // ALEX

These let you control how properties are read and changed.


Class expressions

A class can be declared as an expression:

javascript
const User = class { sayHi() { console.log('Hi!'); } }; new User().sayHi(); // Hi!

Or even given a name that is only visible inside the definition:

javascript
const User = class MyUser { getClassName() { return MyUser.name; } };

Difference between classes and constructor functions

CriterionConstructor functionClass
SyntaxOld, verboseModern, declarative
new requiredYesYes
MethodsVia prototypeInside the class body
Behavior of thisCan be unpredictableClear, standard
Support for extendsManualBuilt in
Private fieldsNoneAvailable (via #)

Important to remember

  1. Classes are not hoisted, like functions are.
javascript
const user = new User(); // ReferenceError class User {}
  1. Inside a class, all methods are non-enumerable, unlike regular properties on prototypes.
  2. Classes are syntactic sugar over prototypes, not a new inheritance model.

Short summary

ConceptWhat it does
classDeclares a class
constructorThe method called on new
extendsInheritance
super()Calls the parent's constructor
staticMethods of the class, not the instance
#fieldA private property
get / setControls access to properties

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.