Molly Thama
Molly Thama

Reputation: 35

How come my inner inner function has access to outside global-scope variables? Isn't that a violation of scope/closure?

I was trying to consolidate my understanding of closure/scoping in JavaScript with the following test code:

var globalM = 1;

function firstFx() {

    function secondFx () {
        console.log(globalM + 1);
    }

    secondFx();
}

firstFx();

I know firstFx would have access to globalM because it's within it's scope. But how is it that my inner inner function, secondFx also has access to the globalM variable? It's reaching 2 levels out, I thought that wasn't possible? Yet the result of 2 is getting logged to the console.

Upvotes: 1

Views: 43

Answers (2)

Guffa
Guffa

Reputation: 700372

There isn't a limitation on the levels of scoping, it goes all the way out to the global scope.

The scope of the code in a function is the scope where the function was created plus its own scope.

Upvotes: 0

Manu Masson
Manu Masson

Reputation: 1737

Your second function has access to it because the variable is global. That means that all scopes anywhere have access to it.

Any scope can access anything that is declared globally or in a level higher. For example in your function the inner function could also access any variables declared in your outer function.

Upvotes: 1

Related Questions