JavaScript Scope Explained

Scope refers to the visibility of variables within code, where within code variables can be accessed and used. Using scope can be important within code, as it’s important to know where you can and cannot access variables it can also be important to purposely make variables not accessible within certain sections of the code. The general rule of thumb is that a variable is access from it’s children scope, but variables cannot be accessed from their parent scope.

Functions within JavaScript can be used to create separate scope. The code below shows a variable called ‘a’ outside of a function and the variable ‘b’ within a function. The variable ‘a’, as it is not declared within any internal scope, it is within the ‘global scope’. The variable within the function can access variables in the global scope, but variables within the global scope cannot access variable inside internal scope.

Other control flow procedures can be used to create internal scope like functions. The scoping of the code below works the same as the above code but it is using a while loop rather than a function. The variable ‘a’ is accessible within the while loop but the variable ‘b’ is not available outside the loop.

The number of nested scopes is not limited, you can have as many internal or child scopes. Variables are accessible is their in the any parent scope, any scope that is above the current level, but not the other way around. The below examples shows how three levels of scope interact and where variables are accessible. The most child scope, the while loop, has access to all the variables but the global scope only has access to variables within the global scope.

Leave a Reply