3

i have this piece of code:

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

why does this code print '2'?

2
  • That looks like the typical example from a tutorial or quiz. Where did you find it? Commented Jul 9, 2014 at 16:17
  • yeah. question is from book (quiz on js). :) Commented Jul 9, 2014 at 17:07

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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();

 })();

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.