DEV Community

thenetaji
thenetaji

Posted on

We’re Already Assigning to this, So Why Return this in method chaining?

This always bugged me.

If I’m already setting stuff on this, like this.name = "Netaji",

the object is already updated. So why do we still return this at the end of the method?

Here’s what I mean:

class User {
  setName(name) {
    this.name = name;  // modifies the object
    return this;       // looks redundant, right?
  }

  setAge(age) {
    this.age = age;
    return this;
  }
}

const u = new User();
u.setName("Netaji").setAge(18);
Enter fullscreen mode Exit fullscreen mode

At first, I thought return this was just some “fancy” coding thing.

But no — it’s actually about what the method call expression gives back.

Try this without returning anything:

class Demo {
  setX() { this.x = 10; }  // no return
}

const d = new Demo();
console.log(d.setX()); // undefined
Enter fullscreen mode Exit fullscreen mode

Even though the object is changed, d.setX() itself returns undefined.

So if you try to chain like d.setX().setY(), boom — it breaks.

That’s the whole point. this updates the object. return this lets you keep using that same object in one smooth chain.

Example of working chaining:

const u = new User();
u.setName("Netaji").setAge(18);
console.log(u.name, u.age); // "Netaji", 18
Enter fullscreen mode Exit fullscreen mode

Top comments (0)