πŸ”΄ Hard'this' BindingπŸ’» Output Question

Chained method calls and this

πŸ’‘

Hint

Fluent/builder pattern: returning this from methods enables chaining. Each call in the chain gets the same object as this.

What does this output?

class Builder {
  constructor() { this.parts = []; }

  add(part) {
    this.parts.push(part);
    return this;  // enables chaining
  }

  build() {
    return this.parts.join(' + ');
  }
}

const result = new Builder()
  .add('A')
  .add('B')
  .add('C')
  .build();

console.log(result);

Correct Output

A + B + C

Why this output?

Explanation: Each .add() returns this (the Builder instance), so the next call still has the same this. .build() reads this.parts which has accumulated all three parts.

Key Insight: Fluent/builder pattern: returning this from methods enables chaining. Each call in the chain gets the same object as this.

More 'this' Binding Output Questions

🟑 MediumMethod extracted from objectβ†’πŸŸ‘ MediumArrow function thisβ†’πŸ”΄ Hardthis in nested functionβ†’πŸ”΄ Hardbind creates new functionβ†’

Practice predicting output live β†’

66 output questions with instant feedback

πŸ’» Try Output Quiz