Let’s understand this with an example. Can you guess what below three console.log prints?
Note: curly braces in console.log print the value with it’s variable name.
What is global scope?
In the above example the variable at line 1 is in global scope. And this variable will be added on window object. Below in fig3 the highlighted section shows how global variable athlete stored on global scope(window).
Global variables exists through out the code execution and can be accessed and modified from anywhere in the code.
What is local scope?
local scope is created when the function got invoked in the code. That means the variables which are defined inside the function are local variables and they are accessible only in this particular scope. When the function execution got over the local scope get destroyed and variables inside this scope get vanished.
In the above example when function printAthleteName() got invoked the local scope is created and variables of this function placed inside the local scope. You can observe this in fig4 highlighted section, How the local scope got created and the variables in it.
Now you might have understood fig2 the output of example1. And what is global scope and local scope.
Let’s see few more examples
In the above example you can observe that global variable athlete is accessed and modified by the local scope.
Note: As mentioned earlier global variables can be accessed and modified from anywhere in the code.
So far you have learned about scope, local scope and global scope. Now we will see how hoisting and scope are related.
So how hoisting and scope are related? The global variable declarations and global function declarations are hoisted to global scope where as local variable declarations and local function declarations are hoisted to it’s local scope. Let’s see this with examples.
In the above example variable declaration a and function declaration b get hoisted to global scope. You can observe this in below fig8 highlighted section.
That’s it. In this post we have covered scope, different types of scopes and how hoisting and scope are related. Hope you have understood the concepts clearly.