❓ Question:
How do you write a JavaScript function that works both like:
sum(2, 3)
and:
sum(2)(3)
function sum(x) {
if (arguments.length == 2) {
return arguments[0] + arguments[1];
} else {
return function(y) {
return x + y;
};
}
}
console.log(sum(2,3));
console.log(sum(2)(3));
🤔 Answer:
Output:
5
5
📌 Explanation:
This function supports two different ways of calling:
1️⃣ Normal function call:
sum(2, 3)
2️⃣ Curried function call:
sum(2)(3)
Both return the same result:
5
---
✅ Step 1:
The function receives the first argument:
x
Inside the function, we check:
arguments.length == 2
This tells us how many arguments were passed.
---
✅ Case 1:
sum(2, 3)
Here:
arguments.length is 2
So:
return arguments[0] + arguments[1];
Which becomes:
2 + 3 = 5
---
✅ Case 2:
sum(2)(3)
First:
sum(2)
Now only one argument is passed.
So the function returns another function:
function(y) {
return x + y;
}
At this point:
x is remembered using closure.
Then:
(3)
calls the returned function with:
y = 3
Now:
x + y
becomes:
2 + 3 = 5
Final output:
5
---
📌 Important Concept:
This is called CURRYING in JavaScript.
Currying means:
Converting a function with multiple arguments into multiple functions that take one argument at a time.
---
✅ Why is currying useful?
Better function reusability
Cleaner functional programming
Partial application of functions
Common in React and JavaScript interviews
---
⚠️ Tip:
Closures make currying possible because inner functions remember variables from outer functions.
👉 This is a very common JavaScript interview question for frontend and MERN stack developers.
#javascript #mernstack #fullstackdeveloper #codinginterview #webdevelopment #js #learncoding #javascript #mernstack #fullstackdeveloper #codinginterview #webdevelopment #js #learncoding
#javascripttips #interviewquestions #JavaScript #Coding #Programming #WebDevelopment #JS #websuccess #websecurity #html #css #frontend #frontenddeveloper #reactjs #angular #vuejs #mobx #redux #reduxtoolkit #frontendmaster #rahul #coding #interviewprep #interview #javascriptinterview
#udemy #leetcode #geektrust #geeksforgeek #hackerrank #codechef #iit #uptu #aktu #programminglife #mernstack #fullstackdeveloper #codinginterview #interviewquestions #webdevelopment #reactjs #nodejs #expressjs #mongodb #learncoding #youtubeshorts #codingtips #programminglife #saikiranyedida #rajshamani #ayejude #apnacollegestudent #akshaymarch7
#CodeVault #Codevalution #GeeksforGeeksVideos #geeksforgeeks