If you want to use closure, then you need return from factorial()
:
function factorial(foo){
let num = foo;
function calculateFactorial(){
for (let i = num - 1; i >= 1; i--) {
num = num * i;
}
return num;
}
return calculateFactorial;
}
let myFunc = factorial(10);
console.log(myFunc());// Output: 3628800
Let me show more simplier and illustrative to me an example:
function fooFunction(foo){
let num = foo;
function calculateFactorial(){
num +=1;
return num;
}
return calculateFactorial;
}
let myFunc = fooFunction(1);
console.log(myFunc()); // Output: 2
console.log(myFunc()); // Output: 3
console.log(myFunc()); // Output: 4
console.log(myFunc()); // Output: 5
Please, read this cool answers at SO about what closure is. These are some highlights:
- Whenever you use function inside another function, a closure is used.
- A closure in JavaScript is like keeping a copy of all the local variables, just as they were when a function exited.
- It is probably best to think that a closure is always created just an entry to a function, and the local variables are added to that closure.
- A new set of local variables is kept every time a function with a closure is called (given that the function contains a function declaration inside it, and a reference to that inside function is either returned or an external reference is kept for it in some way).