Scope
Scope is defined as the availability of variables in other parts of the code.
Types of Scope
In JavaScript, a variable has two types of scope:
- Global Scope
- Local Scope
We are not discussing about Let, because it has block scope. We have discussed about in
Global Scope
Any Variable that can be used in all parts of the code is called Global Scope Variable.
Syntax
Example
Here,
We have declared a variable welcomeText, it is declared outside the function that is why it can be accessed anywhere in the Program.
Local Scope
Any Variable that can be used only inside the function, in which it is declared is called Local Scope Variable.
Syntax
Example
Here,
We have declared a variable welcomeText, it is declared inside the function that is why it can be accessed only inside the function. When we try to use it outside the Function, it will give an Error.
Conclusion
- Global Scope is Accessible Throughout the Program.
- Local Scope is Accessible only inside the Function in which it is defined.
- Block Scope Variable let is only Accessible inside the {} parenthesis in which it is defined.