Nem
Nem

Reputation: 456

Why does my code execute a function defined after the return statement?

i have this piece of code:

(function f(){
    function f(){ return 1; }
    return f();
    function f(){ return 2; }
 })();

why does this code print '2'?

Upvotes: 3

Views: 71

Answers (3)

ckersch
ckersch

Reputation: 7687

In javascript, function definition is hoisted to the top of its containing function.

Your function is interpreted by the browser like this:

(function f(){
    //Functions defined first
    function f(){ return 1; }
    function f(){ return 2; } //<- Hoisted to top, now this is what f is

    //Now the rest of the code runs
    return f();

 })();

Upvotes: 4

Quentin
Quentin

Reputation: 943601

Function declarations are hoisted, so both are processed before the return statement is evaluated.

The second function overwrites the first because they have the same name.

Upvotes: 6

Claudiu Creanga
Claudiu Creanga

Reputation: 8366

Because functions are hoisted and processed before the return statement, so your last function f() returns 2 and it overwrites the first one.

Upvotes: 2

Related Questions