2

I was browsing around the internet and came upon this JavaScript function

   function foo(){
        function bar() {
            return 3;
        }
        return bar();
        function bar() {
            return 8;
        }
    }
    console.log(foo());
    =>8

It's really confusing why this function is returning 8 when it is called. I would assume that this code would run down the contents of the function and stop at return bar();and return 3. What am I missing here?

4
  • 2
    This is because function declarations get hoisted to the top of the block. Commented Oct 27, 2014 at 20:52
  • 1
    functions get hoisted - doesn't matter if it was declared after the statement, it can still be ran. The last bar() overwrites the first. Commented Oct 27, 2014 at 20:52
  • Just curious, is this a question of purely academic value? Why would someone write code like that? Seriously, is there a good reason? Commented Oct 27, 2014 at 20:55
  • @LogicArtist -- Was probably used in an example to demonstrate hoisting. Commented Oct 27, 2014 at 21:00

1 Answer 1

3

This is a result of variable hoisting. function definitions go before anything else. It really looks like this

function foo(){
    var bar;
    bar = function() {
        return 3;
    }
    bar = function() {
        return 8;
    }
    return bar();
}

"Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top." varMDN

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

1 Comment

It might be worth mentioning that using var bar = function () { … } in the original code would actually make a difference here.

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.