InterviewHubPRO
Section Overview
Q500

Question 500 of 521

Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

96%
JavaScript Internals (521 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 521)

How do you implement method chaining in JavaScript?

Method chaining is a pattern where multiple methods are called on the same object sequentially by returning this from each method.

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

   add(num) {
     this.value += num;
     return this; // Enable chaining
   }

   subtract(num) {
     this.value -= num;
     return this;
   }

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

   divide(num) {
     this.value /= num;
     return this;
   }

   getResult() {
     return this.value;
   }
 }

 const result = new Calculator(10)
   .add(5)
   .multiply(2)
   .subtract(3)
   .getResult();

 console.log(result); // 27

Advanced pattern with error handling:

javascript
 class QueryBuilder {
   constructor() {
     this.query = '';
     this.params = [];
   }

   select(...fields) {
     this.query = `SELECT ${fields.join(', ')}`;
     return this;
   }

   from(table) {
     this.query += ` FROM ${table}`;
     return this;
   }

   where(condition, ...params) {
     this.query += ` WHERE ${condition}`;
     this.params.push(...params);
     return this;
   }

   build() {
     return { query: this.query, params: this.params };
   }
 }

 const query = new QueryBuilder()
   .select('id', 'name', 'email')
   .from('users')
   .where('age > ?', 18)
   .build();

Immutable chaining pattern:

javascript
 class ImmutableArray {
   constructor(arr = []) {
     this.arr = arr;
   }

   map(fn) {
     return new ImmutableArray(this.arr.map(fn));
   }

   filter(fn) {
     return new ImmutableArray(this.arr.filter(fn));
   }

   value() {
     return this.arr;
   }
 }

 const result = new ImmutableArray([1, 2, 3, 4])
   .map(x => x * 2)
   .filter(x => x > 4)
   .value(); // [6, 8]