Sergey Metlov
Sergey Metlov

Reputation: 26311

Declaration after return statement

function f() { 
    return f1(); 

    function f1() { 
        return 5; 
    } 
}

f(); // returns 5

Why this works? What are benefits of declaration local functions after return? Is this good practice?

Upvotes: 5

Views: 279

Answers (1)

user113716
user113716

Reputation: 322542

It works because function declarations are all evaluated on a first pass by the interpreter, so you could place them all at the end of the function if you want, and they will work as though they were at the top.

No benefits. Just a preference. I prefer to have the return statement at the end of a function. Seems clearer to me.

Upvotes: 7

Related Questions