JavaScript OOP & Classes Interview Questions and Answers

Explain object-oriented programming in JavaScript, class syntax, constructors, and core OOP principles.

Frequently Asked Questions

Important questions are highlighted in the sections below; select one to jump to its answer.

Theoretical JavaScript Interview Questions

OOP in JavaScript is a way of structuring code around objects that bundle data and behavior together. Rather than scattered functions and variables, you model things as objects with properties and methods - a User object knows its own name and can log itself in. JavaScript does OOP differently from Java or C++ since it's prototype-based under the hood, but the ES6 class syntax makes it feel familiar.

The 6 OOP principles are: Encapsulation (bundling data and methods, hiding internals), Abstraction (exposing only essential features), Inheritance (child classes reuse parent behavior), Polymorphism (objects of different types used interchangeably), Composition (building from smaller objects), and Interface (defining interaction contracts).

A Class is a blueprint for objects. An Object is an instance with specific state. Encapsulation hides internal implementation details behind a public interface (e.g. a bank account exposes deposit/withdraw but hides balance logic). Abstraction focuses on what something does (e.g. a play button). Inheritance lets child classes reuse parent behavior. Polymorphism lets different object types be used through a common interface.

Inheritance in JavaScript works through the prototype chain. When you access a property, JavaScript looks up the chain until it finds it or reaches null. Use Object.create(parent) to inherit from a prototype, constructor functions with prototype assignment, or ES6 class with extends and super().

Prototypal inheritance is a mechanism where objects inherit properties and methods directly from other objects through the prototype chain. Each object has an internal [[Prototype]] link. If a property is not found on the object, JavaScript searches up the prototype chain until it finds it or reaches null.

Prototypal inheritance can be achieved using Object.create(parent) to set a prototype, using constructor functions with Child.prototype = Object.create(Parent.prototype), or using ES6 class with extends keyword. The class syntax is the most readable and is syntactic sugar over prototype-based inheritance.

A constructor function is a function used with the new keyword to create and initialize objects. It is named with an uppercase letter by convention. When called with new, a new object is created, this is bound to it, properties are assigned, and the object is returned automatically.

ES6 classes provide a cleaner, more familiar syntax for creating objects and implementing inheritance in JavaScript. They use the class keyword to define blueprints, constructor() for initialization, and the extends keyword with super() for inheritance. Internally, they still use prototypal inheritance.

The prototypal chain is the series of linked [[Prototype]] references that JavaScript traverses when looking up a property or method. It starts at the object itself, then moves to its prototype, then to the prototype's prototype, and so on until Object.prototype (whose [[Prototype]] is null).

Getters (get keyword) and setters (set keyword) in ES6 classes are special methods that control access to object properties. A getter retrieves a value and a setter updates it. They allow validation, computed values, and encapsulation. Access them like regular properties: obj.name.

If a property and its getter/setter share the same name, accessing the property calls the getter, which tries to access the same property, which calls the getter again, creating infinite recursion. This results in a 'Maximum call stack size exceeded' error. Use a backing property with a different name, often prefixed with an underscore.

A static method is defined with the static keyword inside a class and belongs to the class itself rather than to any instance. It is called directly on the class (MyClass.myMethod()) without needing to create an instance. Static methods are useful for utility functions related to the class.

Use the module pattern with an IIFE to create a closure where private variables and functions are inaccessible from outside. In ES6 classes, use the # prefix syntax for truly private fields and methods that cannot be accessed outside the class body.

The `constructor` method initializes a new instance when code calls the class with `new`. If it is omitted, JavaScript provides a default constructor.

An ordinary method declared in a class body is placed on that class's prototype, so instances can share the same method function. It is not recreated as an own property on every instance.

`new` creates an instance, connects it to the class prototype, and runs the constructor with that instance as `this`. A class constructor must be called with `new`.

In a call such as `instance.method()`, `this` inside an ordinary method refers to `instance`. Extracting the method and calling it separately can change its `this` value.

JavaScript Practical and Coding Interview Questions

Problem: Use a private class field and validated deposit and withdraw methods. Return the updated balance after each operation.

javascript

class BankAccount {
  #balance = 0;

  deposit(amount) {
    if (!Number.isFinite(amount) || amount <= 0) throw new RangeError('Deposit must be positive');
    this.#balance += amount;
    return this.#balance;
  }

  withdraw(amount) {
    if (!Number.isFinite(amount) || amount <= 0 || amount > this.#balance) {
      throw new RangeError('Invalid withdrawal');
    }
    this.#balance -= amount;
    return this.#balance;
  }
}

const account = new BankAccount();
console.log(account.deposit(50));
console.log(account.withdraw(15));

Problem: Implement add and multiply methods that return the instance, plus a value method. Chain the operations and log the result.

javascript

class Calculator {
  constructor(value = 0) {
    this.total = value;
  }

  add(value) {
    this.total += value;
    return this;
  }

  multiply(value) {
    this.total *= value;
    return this;
  }

  value() {
    return this.total;
  }
}

console.log(new Calculator(2).add(3).multiply(4).value());

Problem: Create a class that accepts finite Celsius values, exposes a Fahrenheit getter, and rejects invalid assignments. Demonstrate the conversion.

javascript

class Temperature {
  constructor(celsius) {
    this.celsius = celsius;
  }

  get celsius() {
    return this._celsius;
  }

  set celsius(value) {
    if (!Number.isFinite(value)) throw new TypeError('Temperature must be finite');
    this._celsius = value;
  }

  get fahrenheit() {
    return this._celsius * 9 / 5 + 32;
  }
}

const temperature = new Temperature(20);
console.log(temperature.celsius, temperature.fahrenheit);

Problem: Define a `Rectangle` class that stores width and height and has an `area()` method. Create a 4-by-3 rectangle and log its area.

javascript

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }
}

const rectangle = new Rectangle(4, 3);
console.log(rectangle.area());