Can anyone please explain this code?
(function f(){
function f(){ return 1; }
return f();
function f(){ return 2; }
})();
I really didn't understand the recursion. I thought it will return 1 because it already returned f(), but it returned 2.
that's not a recursion ... that's just overriding names within a scope ...
if the interpreter would just use some type of atomic bursts without any optimizations it probably would return 1.
(function f(){
function f(){ return 1; }
return f();
function f(){ return 2; }
function f(){ return 'the function name f within this scope is overwritten again'; }
})();
apoorv barwa
Technology enthusiast And Web Developer
As said before that this is not a recurrsive problem but just how hoisting works with JS.
The code posted you would be executed in the following manner.
(function f(){ function f(){ return 1; } function f(){ return 2; } return f(); })();So when the execution reaches the return statement the definition of the function is the second one and hence your return statement is 2 and 1 will never be returned.