What is the scope?
var. We will get into this in a second. Before that let’s see an example of these different scopes.
Here, every variable declared outside the function
testScope has a global scope. And any variable declared inside the function
testScope has a functional scope. But if any variable is declared inside curly braces then it has its own scope which is called block scope. But what is meant by these scopes and who has access to whom? Let’s see!
This will console log:
This means we can access the global variable from any scope. You can think of global scope as the group chat! Everyone has access to the messages!
In the case of functional scope, we’ll only have access to the functional scoped variables only if we are inside the function. Here is an example:
Even if we have nested scopes inside a function, we’ll still have access to the functional scoped variable.
At this point, we should have a clear idea of what global and functional scopes are! If not, take a pause and read the code snippets again!
BUT variables declared with keyword
var are not block-scoped. So,
If you are interested in learning more about the differences between
const you can read this article.
Now that we have a clear understanding of all the scopes, let’s see an example with nested scopes.
innerMostFunction() has access to all the variables of its outer scopes. But
innerFunction() can’t access its inner scope variables.
To sum up the idea of scoping, we can say:
- Global scoped variables can be accessed from anywhere in the codebase.
- Block scopes variables are only accessible within the block.
- The variables of the outer scope are accessible inside the inner scope.
What is closure?
Let’s understand the definition with some examples. We know that the outer scope variable can be accessed from the inner scope when the functions are nested. So far, we have been invoking the inner functions inside the outer function. What if we invoke the inner function outside the outer function?
Here, we are returning the
innerFunction and then saving its reference to the test variable. Then when we call
test(), it still has access to the
test() is a reference to the instance of the function
innerFuntion() that was created when
testScope() was run. The
innerFuntion() maintains its lexical environment and that’s why when
test() is run, it still has access to
If you have any questions feel free to reach out to me on LinkedIn.