Simple Explanation of Javascript Scopes (Global Scope and Local Scope)

Simple Explanation of Javascript Scopes (Global Scope and Local Scope)

Simple Explanation of Javascript Scopes (Global Scope and Local Scope)

As a beginner developer; you can easily mess up your codes if you ain't familiar with javascript scopes! Especially when working with data that keeps changing or conditional statements.

So, spending few minutes to understand how these scopes work might save you a long night of wondering why your codes are acting all crazy! (Thank me later..)

Let us Dive into the world of Scopes;

Scope in Javascript simply refers to the ways to access your codes;

Story Time

Using the case scenario of the way a network Wifi works;

A building that has general wifi can be accessed by different rooms in the building. let's call that a **global scope **(because it is available everywhere within the building)

Still, each room decides to get its own Wifi, let's call that a **local scope **(because the wifi is only available to those in that room and not outside)

Definitions and Examples:

Global Scope

Global scope refers to a particular set of commands or declarations that can be accessed anywhere within a script of codes;

var corridor= "yellow";   //global scope

function getColor() {
console.log(corridor);    //returns yellow
}
getColor();
------------------------

var corridor= "yellow";     //global scope
var room = "white";        //global scope

function getColors() {
console.log(corridor);    //returns yellow
  function useColors(){
  console.log(`The room is ${room} while the corridor is ${corridor}`);
// returns The room is white while the corridor is yellow
  }
  useColors();
}
getColors();

in this example; the variable corridor and variable room have a global scope and therefore their values are accessible at any point of the script.

Local Scope

** Local scope** refers to a particular set of commands or declarations that can only be accessed within the function in which they are defined;

function getColor() {
  var corridor= "yellow";        //local scope
  console.log(corridor);        //returns yellow
}
 console.log(corridor); // returns corridor is not defined

getColor();

In this example, we can see that the corridor variable only exists within the getColor function and not beyond; as trying to get that corridor variable outside that function would only return as undefined!

Local scope can be divided into, Function scope and Block scope.

Function Scope

Function scope refers to the area that exists between a function that a particular set of commands or declarations can only be accessed.

function house(){ 
   .........            //function scope                        
}                              

house();

Block Scope

** Block scope ** refers to the area between two curly brackets {----} that a particular set of commands or declarations can only be accessed and it usually occurs when declaring conditional statements such as if-else, switch or for and while loops.

function house(){ 
 ......               //function scope      
    if(true){                
    ......         //block scope
    }                               
    if(!false){ 
    .....          //block scope
    }                              
}                              

house();

To further explain the difference between these local scopes; Let's take a look at Var, Let and Const (the three ways in which a variable can be declared in javascript)

  1. Var is used in a Function Scope

  2. Let is used in a Block Scope

  3. Const also used in a Block Scope

function house(){                  
    if(true){                       
      var corridor = "yellow";        
      const rooms = "white";     
      let kitchen = "blue";
};                                
    console.log(corridor);       //returns yellow
    console.log(rooms);         //returns rooms is undefined
    console.log(kitchen);       //returns kitchen is undefined
}                                

house();

In this example; the reason only the corridor variable was printed out was because of the way it was declared; that is the use of var and var being a function scope can exist at any point within the function it was created in. But const and let being a block scope does not have such free movement, and can only be used within the block {----} it was created and not outside.

 function house(){                  
    if(true){                               
      var corridor = "yellow";        
      const rooms = "white";     
      let kitchen = "blue";
        console.log(corridor);          //returns yellow (function scope)
        console.log(rooms);            //returns white (block scope)
        console.log(kitchen);          //returns blue (block scope)
};                                        
    if(!false){                               
      console.log(corridor);          //returns yellow
      console.log(rooms);            //returns white is not defined
      console.log(kitchen);          //returns blue is not defined
    }                                           
    console.log(corridor);          //returns yellow
    console.log(rooms);            //returns white is not defined
    console.log(kitchen);          //returns blue is not defined
}

house();

Here, we can see the behaviour of the function scope and the block scope using the var let and const in a function.

Therefore, since the development of ES6 javascript; developers have been advised to try as much as possible to avoid using var to declare a variable, as it has the tendency of re-calling already used variables; thereby messing up one's codes.

CONGRATULATIONS! You made it to the end of the Article

if you enjoyed learning and find it useful please do like and share so that, it reaches others as well..

Thanks for reading 🤝

Let me know in the comment section if you have any doubts or feedback.

See you in my next Blog article, Take care!!

Happy Learning ❤❤