What is scope and why do we need it?
scope will make your code more professional, reduce errors and help you make powerful programming design patterns with it.
In the above example, we declaring two variables:
functionVariable then we simulate a console.log() to output the types of each of variable. Notice one is
string, and the other is
Lastly, we call the
whatsInMyGlobalScope function, which evaluates the availability of those two variables inside the function scope.
In Our Global Scope:
globalVariableis defined (it’s a string) because it’s declared in the global scope (it would also be defined if it was in the function scope).
functionVariableis undefined because it is only declared in the function scope.
In Our Function Scope:
globalVariableis defined because it’s declared in the global scope, same as above. It’s not defined in the function scope, but it is available to the function scope.
functionVariableis defined in the function scope if it is only referenced in the function scope.
So, the inner scope can access any variables/functions that are declared outside of their scope. In our case, the inner scope is the function scope, and the outer scope is the global scope (there is no other higher level).