Local Scope

Any declaration inside a function is called local scope
Every function has its own separate local scope
Anything declared in the local scope can only be accessed from inside the function.
There are two types of local scope: Function scope and Block scope
Block scope was added in ES 2015.


var global1;          // global scope 
function myfinc() {
   var local1; // local scope
}

Function Scope

Anything declared inside a function are bound to their respective functions and are not accessible outside that function.

function myfinc1() { 
   var local1; // local scope
}
function myfinc2() {
   var local2; // local scope
}


Block Scope

Block scope is the area inside curly brackets
The inside of an "if" or "switch" condition would be considered block scope
The inside of a "for" or "while" loop would be considered block scope.
In ES 2015 the const and let keywords can be used to declare variables in block scope.


function myfinc() { 
   // block1 is not accessible
   // block2 is not accessible
   if ( true ) {
      let block1;
   }
   while ( false ) {
      const block2;
   }

When you declare variables using "var" there is only function scope. There is no block scope

function myfinc() { 
   // block3 is accessible
   // block4 is accessible
   if ( true ) {
      var block3;
   }
   while ( false ) {
      var block4;
   }



© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext