Skip to main content

What is a class in JavaScript?

A class in JavaScript is a syntactic way to describe objects and their behavior (methods), introduced in the ES6 (ECMAScript 2015) standard. It is syntactic sugar over the prototypal inheritance that already existed in the language. In other words, under the hood classes work through the same prototype mechanisms.


Key Features of a Class

  1. Declaring a class:
javascript
class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hi, my name is ${this.name}`); } } const user = new Person("Alice", 25); user.greet(); // Hi, my name is Alice
  • The constructor() method is called when a new instance is created (new Person()).
  • this inside the constructor refers to the object being created.

Class Inheritance

Classes can inherit properties and methods from other classes using the extends keyword.

javascript
class Animal { speak() { console.log("The animal makes a sound"); } } class Dog extends Animal { speak() { console.log("The dog barks"); } } const dog = new Dog(); dog.speak(); // The dog barks

If you need to call the parent's method, use super():

javascript
class Dog extends Animal { speak() { super.speak(); // calls the parent's method console.log("Woof woof"); } }

Static Methods and Properties

Sometimes a method belongs not to a specific instance, but to the class itself:

javascript
class MathUtils { static square(n) { return n * n; } } console.log(MathUtils.square(5)); // 25

Static methods cannot be called on an instance (new MathUtils()), only on the class itself.


Getters and Setters

Let you control access to a class's properties:

javascript
class User { constructor(name) { this._name = name; } get name() { return this._name.toUpperCase(); } set name(value) { this._name = value.trim(); } } const u = new User(" Alice "); console.log(u.name); // ALICE

Private Fields and Methods

The # syntax makes a property or method inaccessible from outside:

javascript
class Account { #balance = 0; deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const acc = new Account(); acc.deposit(100); console.log(acc.getBalance()); // 100 // acc.#balance - Error: private property

Summary

FeatureDescription
constructor()Initializes the instance
extendsInheritance
superCalls the parent's constructor or method
staticMethods on the class, not the instance
get / setControls access to properties
#Private fields and methods

Short Answer

Interview ready
Premium

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