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
Trevor Johnson
14,427 PointsClosures in JavaScript!
Hey, so I was working on a coding challenge, and part of the challenge required that I understand how to properly use closures. I read through an MDN article here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures and it was helpful, but I don't really understand why my code works.
Here is my closures function that I could use some help in understanding why it works. The part that I don't get is the way the second number is added to the end of addTogether(2)(9).
function addTogether() {
var args = Array.prototype.slice.call(arguments);
var isNumb = function Numb(args) {
for (i = 0; i < args.length; i ++) {
if (!Number.isInteger(args[i])) {
return undefined;
}
}
return true;
};
var addNew = function(x) {
return function(y) {
if (!Number.isInteger(y)) {
return undefined;
}
return x + y;
};
};
var addTwo = function(a,b) {
return a + b;
};
if (!isNumb(args)) {
return;
} else if (args.length === 1) {
return addNew(args[0]);
} else if (args.length > 1) {
return addTwo(args[0], args[1]);
}
}
addTogether(2)(3);
1 Answer
Steven Parker
243,318 PointsThis is a function that is returned by another function being called.
It looks odd, but think about it in steps:
- the function addTogether is called and given the argument
2 - it returns another function (the anonymous one inside addNew)
- then that returned function is called and given the argument
9
Make sense now?