Skip to main content

Block scope, Function Scope, Lexical Scoping in Javascript

Function Scope means that any variable which is defined within a function is visible within that entire function not out side of the function.

 function funScope () {
  var iAmLocalScope = "I am Local";
  console.log("Function local scope: " + iAmLocalScope);
}

funScope();

console.log(iAmLocalScope);
// -> "ReferenceError: iAmLocalScope is not defined

Block Scope, a variable scope is limited by the block where it is declared in. A block is usually means between {} curly braces or loop variables for(;;){}.It is not possible to create a block scope in javascript. And here the example

var i = 1; // <--- In here first i is define and initialize to 1

for (var i = 0; i < 10; i++) {
   // <-- Here also define the same variable i with block for loop{}
}

console.log(i); // <-- 10

 //if block scope exist then i value
//should print here 1 instead of 10.

But This behavior changes, when using the let declaration introduced in ECMAScript 2015.

 

var i = 1; // <--- In here first i is define and initialize to 1

for (let i = 0; i < 10; i++) {}
// <- using by let local scope create within block scope

console.log(i); // <-- Thats why i value is 1 instead of 10

Lexical Scoping(Static Scoping or Closure) : If a child function define and call within a parent function scope then child function can access all the local variable within the parent function scope even if the parent function has returned

var adder = function (loc) { 

  return function (summand) {
    loc += summand;
    console.log(loc);

  };
}; 
// <- we call the annonymous function      
//    and assign the returned function to adder 

var inner = adder(1); // -> Now local variabe loc == 1

inner(5); //-> Now local variabe loc == 6
inner(4); //->Now local variabe loc == 1