Global and Local scopes of Variables
Scope of a variable will depends on the place where is is standing and keyword used while defining it. There are two kinds of scopes:
- Global
- Local
Thumb rules:
- Code in the global scope cannot use any local variables.
- However, a local scope can access global variables.
- We can use same variable name for global and local scopes. So that clash will not be there while accessing it.
Global variables are of high priority than local variables.
Global scope: A variable will be global
- If it is declared outside of all the functions.
- If it declared using global keyword.
Examples-
Here we defined a local variable var1 and trying to access it outside the function. It will throw an error.
Here we defined a global variable var1. And trying to access it inside and outside the function. Since it is declared as global, we are able to access it.
Below we declared both global and local variables with same names. However when accessing inside function local variable will get more priority and outside of the function global will get called.
Declaration using Global keyword:
When we declare a variable as global inside the function then we will be to modify a global variable from within a function.
Checkout below code , var1 is declared outside function hence scope is global. However we modified the value inside function by defining same variable as global. Hence it returned value assigned inside the function.
Do try other possibilities as well!!