Bummer! You have been redirected as the page you requested could not be found.

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

JavaScript

Function inside a function

function multiplier(factor) {
  return function(number) {
     return number*factor;
  };
}

var twice = multiplier(2);
console.log(twice(5));

// -> 10

Can't understand why the result printed to the console was 10. The argument of var twice shouldn't replace 'factor'? Thanks :)

function multiplier(factor) {
  return function(number) { <-- 3. The function, multiplier, returns an anonymous function. 
     return number*factor;  <-- 2. It is then passed along to the anonymous function and assigned to factor.
                            <-- 6. The anonymous function returns the number passed to it multiplied factor.
  };
}

var twice = multiplier(2);   <-- 1. Pass in a number to the multiplier function
                             <-- 4. Anonymous function is assigned to variable twice.

console.log(twice(5));       <-- 5. Calling function, twice, and passing in the number 2.

// -> 10                     <-- 7. So passing 2 to multiplier, and 5 to twice, returns 10. 

1 Answer

Clayton Perszyk
MOD
Clayton Perszyk
Treehouse Moderator 49,057 Points

Giovanni,

What you have created is a closure; even after the outer function has returned, the inner function retains a reference to any variables, including arguments/parameters, created in the context of the outer function. So, when you call multiplier(2), its returning a function that has access to the factor parameter, which has the value 2; when you call twice(5), 5 is being passed as the number argument (i.e. nothing is replacing factor, which is still 2); as such the call to twice(5) is returning the number, 5, multiplied by the factor, 2. What were you expecting as the value returned from twice(5), if not 10.?

Best,

Clayton