Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Tani Huang
6,952 PointsClosure..how it works..
How it works...
function makeAdder(x) {
return function(y) {
return x + y;
};
}
var add5 = makeAdder(5);
var add10 = makeAdder(10);
console.log(add5(2)); // 7
console.log(add10(2)); // 12
This is my understanding..
1) base on var add5 = makeAdder(5); If put 5 to function makeAdder(x) I get 5 + y, what is the value of y ? undefined ?
2) console.log(add5(2)); x is already exist 5, how can I put the value 2 and get the answer of 7?
1 Answer
Kris Byrum
32,636 Pointsy hasn't been declared yet so it's nothing at the moment.
When you call this type of closure what you're doing is setting the local scope. The local scope in this instance will set
xto 5. You don't have a way to change that so x will always be 5.
The return of the makeAdder function will be another function. So whatever variable you assign makeAdder to, will now evaluate to that return function.
If you want to get 7, then you simply pass in 2 to the variable you make for makeAdder. (keep in mind you can call it like makeAdder(x)(y) and it will do the same. No need to assign it to a variable)
eg.
function closure(x) {
const localScopeVar = x
return function(y) {
return localScopeVar + y
}
}
const firstCall = closure(5) // evaluates to function(y) { return 5 + y }
const secondCall = firstCall(2) // evaluates to 7