jssumfactoryclosurejs method
how to sum a 2 num
This solution uses the Factory Function pattern along with Closures.
MN
Messi Nisar
Jul 10, 20261 min read10 views
js
function Code(num1) {
return {
sum(num2) {
return num1 + num2;
},
subtract(num2) {
return num1 - num2;
},
multiply(num2) {
return num1 * num2;
},
divide(num2) {
return num1 / num2;
},
};
}
const result = Code(5);
console.log("Sum:", result.sum(5));
console.log("Subtract:", result.subtract(5));
console.log("Multiply:", result.multiply(5));
console.log("Divide:", result.divide(3));
Explanation
This solution uses the Factory Function pattern along with Closures.
A factory function is a function that creates and returns an object containing properties and methods. Each time the function is called, it returns a new object.
In this example:
Code(5)is called, wherenum1is5.- The outer function returns an object with four methods:
sum(),subtract(),multiply(), anddivide(). - We store the returned object in the
resultvariable. - We then call the object's methods and pass another value (
num2) to perform different operations.
The interesting part is that all of these methods can still access num1 even after the Code() function has finished executing. This happens because of closures. Each method "remembers" the value of num1 from its outer scope.
Concepts Used
- ✅ Factory Function
- ✅ Closure
- ✅ Lexical Scope
- ✅ Object Methods
- ✅ Encapsulation (keeping
num1private inside the closure)
Written by
MN
Messi Nisar