I was taking a small test online and there was this code:
function getFunc() {
var a = 7;
return function(b) {
alert(a+b);
}
}
var f = getFunc();
f(5);
I would like to know why I can't call getFunct(5) directly for example.
I don't understand the last two lines.
Why do I need to assign the function to a variable. What happens when doing f(5)?
How does JS interpret that the 5 is a variable for the inner function and not the outer?
getFunc.getFuncreturns a function you call with a parameter. Look at the signature ofgetFunc: is there a parameter?getFuncreturns afunction. So,fis just the inner function where the contextualais 7. You shouln't directly call it, because the call signature ofgetFuncjust doesn't accept any argument, so calling it with any argument will do nothing.