Forem

Cover image for How I Bombed a JavaScript Interview and Learned About Function Chaining the Hard Way
NoobDev
NoobDev

Posted on

How I Bombed a JavaScript Interview and Learned About Function Chaining the Hard Way

The Painful Interview Moment

You know that sinking feeling when you’re staring at your screen, the interviewer waiting, and your brain just decides to go on vacation? That was me in a JavaScript interview.

The task? Create a simple function that supports method chaining.

My response? Blank stares, a sweaty keyboard, and a strong urge to close the laptop and run away.

Well, I bombed it. But instead of sulking, I decided to master function chaining like a boss. If you’ve ever struggled with this concept, this blog is for you.


What is Function Chaining in JavaScript?

Function chaining is when you call multiple methods on an object, one after another, in a single statement. You’ve seen it in libraries like jQuery or Lodash:

$('.element').addClass('active').fadeIn().css('color', 'red');
Enter fullscreen mode Exit fullscreen mode

Each method returns the object itself, allowing the chain to continue. But how do we implement this ourselves?


The Classic Object-Oriented Approach

The simplest way to implement chaining is to have methods return this (the object itself):

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

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

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

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

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

  result() {
    return this.value;
  }
}
Enter fullscreen mode Exit fullscreen mode

Each method returns this, which allows us to chain method calls.


Real-World Use Cases for Function Chaining

Sure, the calculator example is cool, but let’s get real—where can function chaining actually help? Here are three practical, real-world implementations:

1. DOM Manipulator

Instead of writing repetitive DOM queries, let’s create a neat utility:

class ElementWrapper {
  constructor(selector) {
    this.element = document.querySelector(selector);
  }

  addClass(className) {
    this.element.classList.add(className);
    return this;
  }

  removeClass(className) {
    this.element.classList.remove(className);
    return this;
  }

  setText(text) {
    this.element.textContent = text;
    return this;
  }
}

// Usage:
const button = new ElementWrapper("#myButton");
button.addClass("active").setText("Click Me!");
Enter fullscreen mode Exit fullscreen mode

2. Event Emitter

A simple implementation of an event-driven system with method chaining:

class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);
    return this;
  }

  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(data));
    }
    return this;
  }
}

// Usage:
const emitter = new EventEmitter();

emitter.on("message", msg => console.log("Message received:", msg)).emit("message", "Hello!");
Enter fullscreen mode Exit fullscreen mode

3. CSS Builder

Dynamically generate inline styles with method chaining:

class StyleBuilder {
  constructor() {
    this.styles = {};
  }

  set(property, value) {
    this.styles[property] = value;
    return this;
  }

  remove(property) {
    delete this.styles[property];
    return this;
  }

  build() {
    return Object.entries(this.styles)
      .map(([key, value]) => `${key}: ${value}`)
      .join("; ");
  }
}

// Usage:
const styles = new StyleBuilder()
  .set("color", "red")
  .set("font-size", "16px")
  .remove("font-size")
  .build();

console.log(styles); // "color: red"
Enter fullscreen mode Exit fullscreen mode

Other Common Chaining Examples

Here are some common areas where method chaining is widely used:

  • Logging utilities (e.g., .info().warn().error()) for structured logging.
  • Animation libraries (e.g., custom .fadeIn().move().scale() chaining).
  • Query builders (used in SQL ORMs like Knex.js).
  • HTTP request builders to construct API requests dynamically.

If you're interested in learning more about any of these common examples, let me know!


What I Learned After Bombing the Interview

  1. Panic ruins everything. If I had stayed calm and broken the problem down, I could have written the solution.
  2. Returning this is the key to chaining. As long as methods return the object, chaining works.
  3. Practice matters. The more I implement chaining, the more natural it feels.
  4. Multiple approaches exist. OOP, functional programming, and prototype-based solutions all work.

Final Thoughts

I bombed my interview, but I walked away learning something valuable. If you ever get asked about function chaining, you won’t have to suffer like I did.

And who knows? Maybe next time, I’ll ace it. 🚀

Top comments (0)