Scope.....

Scope.....

What is Scope in Programming ?

Scope is all about current context of execution and values available in the context. If you try to access the values or variables that are not in current context you will get an error. The current context may be a global scope or function scope or block scope.

Why scope is important ?

  • Scope is very help full in avoiding bugs and errors.
  • Scope of increases readability of code.
  • Scope make sure we use variables to correct context.

Types of Scope

Global Scope

Variables declared in global scope are visible and can be accessed every where (i.e every scope). global variables are declared out side function body.

var a = 10;  //global variable 
var b =20;  // global variable
function sum(a, b){
  // function scope
}
function product(a, b){
  // function scope
}

In the above code a and b are global variables. They can be accessed in sum() and product() also which are function scope.

Function Scope

Variables declared inside function body belongs to that function's execution context only. These variable can't be accessed globally or in any other function.

var a = 10; // global variable
var b = 20; // global variable
function sum(a, b){
let totalSum; // function scope variable
totalSum = a + b;
}
console.log(totalSum) 
// output : error

In the above example totalSum was declared inside function whose scope is limited to function's execution context only.For printing out totalSum we used it global context, so it gives reference error .

Block Scope

Usually in any programming language scope is considered as {} context. To explain more about block scope I will definitely need an example.

var a = [10,12]; // global variable
for(let c of a){
   console.log(c); //1
   // works fine
}
console.log(c); //2
// error

In the above example , c at position 1 is belongs to block scope.When tried to access at position 2 it throws error.

Summary

The scope is the current context of execution in which values and expressions are "visible" or can be referenced. If a variable or expression is not in the current scope, it will not be available for use. Scopes can also be layered in a hierarchy, so that child scopes have access to parent scopes, but not vice versa.