This question is testing method chaining + object design.
🔹 Given Code
console.log(
x.init(2).add(4).mul(3).div(2).disp()
);
To answer this, we must first understand what x is.
✅ What is x?
x is an object that:
- Stores an internal value
- Each method updates that value
- Each method returns
thisto allow chaining disp()returns the final value
This pattern is called a fluent interface / method chaining.
✅ Definition of x
const x = {
value: 0,
init(n) {
this.value = n;
return this;
},
add(n) {
this.value += n;
return this;
},
mul(n) {
this.value *= n;
return this;
},
div(n) {
this.value /= n;
return this;
},
disp() {
return this.value;
}
};
🔍 Step-by-Step Evaluation
x.init(2) // value = 2
.add(4) // value = 6
.mul(3) // value = 18
.div(2) // value = 9
.disp(); // returns 9
✅ Final Output
9
🧠 Why This Works (Important Concept)
- Each method returns
this thisrefers to objectx-
Enables chaining like:
x.method1().method2().method3()
This is commonly used in:
- jQuery (
$('div').addClass().css()) - Lodash / utility libraries
- Builder patterns
- Configuration APIs
🎯 Short Interview Answer
xis an object implementing method chaining by returningthisfrom each method.
The expression evaluates step by step and finally returns9.
⭐ One-line summary
x is a chainable object, and the output is 9.