Imagine Scope as a boundary within that things can be isolated. Like in your colony there are certain areas which has stuffs that are accessible to everyone in your colony. In contrast to that stuffs which are inside your room is not accessible to other apartment people. Scope defines the boundary.
- Global scope
- Local scope
- Closure scope
- Lexical scope
Lexical Scope is introduced all browsers do not support Lexical Scope feature. Therefore, we will talk related to lexical scope in our next article. :) stay tuned.
What is Global Scope
Global scope is available for everyone. The variables inside the global scope are accessible from everywhere.
In our above example
x is declared and instantiated with
20 globally. That is why we can access this value from
window Object is a Global Object and it is within global scope.
When should I create Global Variable
Global Variables are useful to declare something which is very stable and never changes. For example: For your website if you have settings which are needed everywhere then you can create
APP_SETTINGS as a global variable.
What is Local Scope
How to create local scope
When you write a function and declare some variables then Local Scope gets created and function variables are placed inside the local scope. Function arguments are also part of local scope.
In our above example variable
a which a function argument belongs to local scope only. Since local scope is not accessible outside the function therefore, I can not access variable
a from global scope. In
local scope there are 2 variables one is
a and the other variable is
this which is a reference to the
window Global Object. I will explain
this keyword in my next article :)
When should I create Local Variable
Can I access local scope Globally
No, local scope is only accessible within the function.
What is Closure Scope
It is the local scope of a function which is accessible to its children functions. Any variable declared in a function or any arguments in a function is accessible to its children functions and this accessiblity comes from
Closure Scope only. :)
In my above eample function
add has one local scope which has variable
a inside the local scope. The child function of
add function has one local scope which has variable
b inside that additionally, it has access to
Closure Scope also.
Closure Scope gets created within child function and it contains varibles from its parent function.
Well lots of theory ! Now its time for practical problem. I have given a challenge question to you. Please read this problem below and reply your answer and give reason why do you think your answer is correct.
addButtons function is adding 10 buttons in the
list-problem div . Question is what will be the alert message when I click on 9th Button ?
Video on Scope