Global and Local scopes of Variables

By | May 13, 2018

So we are good with functions. Let us learn something called scope of a variable.

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:

  1. Global
  2. 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 then 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. Hence it throws an error.

Here we defined a global variable var1. And trying to access it inside and outside of 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 of 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!!

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.