Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function var in function scope [duplicate]

Tags:

javascript

I thought that

function foo() { return 42; }

is mostly equivalent to

var foo = function() { return 42; }

except that foo.name differs in both cases. But regarding the scope, I thought it would be the same.

However, then I stumbled upon this code:

function demo() {
    return foo;

    function foo() { return 42; }
}

And demo() actually returns the foo function, i.e. demo()() == 42.

So, it seems that function evaluation is probably already done earlier, probably at compile stage.

Is my guess correct? Is that standard? (I'm using V8.)

(I just found this - it might be a duplicate.)

like image 649
Albert Avatar asked Jun 11 '26 13:06

Albert


1 Answers

Functions defined like this:

function foo() { return 42; }

Are hoisted to the top of their containing function.

this looks to be a good article explaining scopes and hoisting.

like image 180
Davin Tryon Avatar answered Jun 14 '26 02:06

Davin Tryon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!