Scope
Last updated
Was this helpful?
Last updated
Was this helpful?
The scope determines the accessibility to variables and functions. If something is "outside of scope" it means we can not access it.
The global scope is the scope that is accessible from anywhere. Anything that is defined outside of a function is a part of the global scope.
Consider this very simple program. It only contains a single variable called planet
. The variable is a part of the global scope because it is defined outside any function.
However, if the variable had been defined inside a function instead it would no longer belong to the global scope.
planet
is no longer in the global scope, but instead constrained to the scope of the universe
function.
In other words, it is inaccessible from the global scope. Which in turn means that the code above would throw a ReferenceError
stating that planet is not defined
.
Another useful (but perhaps counterintuitive) scope is the lexical one. It provides a function within another function access to the scope of the outer function.
Calling the milkyWay
function would log out earth
in the case above.