I want to understand why this code returns number:
(function f(f){
return typeof f();
})(function(){return 1;});
First I assume it will return undefined since function f executes before the last function, but then I run the code with console logs and the result was number. Anyone would mind explaining why this was the output?
f inside the first function’s body refers to the parameter called f. An equivalent version without the confusing shadowing would be:
(function f(g){
return typeof g();
})(function(){return 1;});
And an equivalent version with the IIFE separated into a function definition and a call:
function f(g) {
return typeof g();
}
f(function () {
return 1;
});
(If it’s not clear why this returns 'number', you should review the concept of functions as values before jumping into intentionally more complicated IIFEs with shadowing that also make use of the concept.)