Brief – Javascript Variable Scope

In this article I would be summarizing important points to keep in mind when thinking of javascript variable with respect to their scope.

For a long time object oriented programmer coding in languages like C# (such as me), the concept of JS variable scope was somewhat surprising at first. Hence, I thought it is important to look at each little detail in the light of the day to really understand and embrace it.

Below is a list of bullet points and code snippets I worked out to understand the variable scope which I am sharing with you as a reference.

  • Javascript variables do not have a block level scope. This is unlike most of the other programming languages such as C#, Java, etc. A block level scope is defined by simple curly braces, or inside a conditional statement or inside a loop.
{
   var myMessage = 'Hi, How are you?';
}
//The variable myMessage is available even outside the scope defined by curly braces
console.log(myMessage);  //Writes 'Hi, How are you?' to console

if(true){
   var welcomeMsg= 'Welcome to my blog';
}
//The variable welcomeMsg is available even after if scope is finished
console.log(welcomeMsg);//Writes 'Welcome to my blog' to conosle


for(var i=0; i<5;i++){
  console.log('inside for - The value of i is ' + i);
}
//The variable i is accessible even after for loop has ended. It holds the last value assigned to i.
console.log('outside for - The value of i is ' + i); //Writes 'outside for - The value of i is 5' to console
  • Javascript variables have a function level scope. Variables declared inside a function are local variables. They are accessible only inside the same function or inside a nested function or inside a nested object.
function myFunc(){
    var myMessage = 'This is a message';
    console.log(myMessage);
}

myFunc(); //Writes 'This is a message' to console
cosnole.log(myMessage)//Throws error - myMessage is not defined
  • The function on the other hand have access to variables in three types of scope
    • local scope (declared inside same function)
    • outer scope (i.e. outer function)
    • global scope (declared outside any functions and tied to global scope i.e. window object. Or declared inside a function without use of var keyword)
var globalMsg = 'This is a message tied to global scope'

function myOuterFunc(){
   console.log(globalMsg );
   var outerMsg= 'This is a message inside myOuterFunc';

   function myInnerFunc(){
       var localMsg = 'This is a message inside myInnerFunc';
       console.log(outerMsg);
       console.log(localMsg);
   }

return {myInnerFunc};
}

var myObj = myOuterFunc();//Writes 'This is a message tied to global scope' to console.
myObj.myInnerFunc(); //Writes 'This is a message inside myOuterFunc' followed by 'This is a message inside myInnerFunc' to console
  • The variable in outer scope can be overridden inside function scope. If declared with var keyword, it makes outer scope variable is hidden.
var myName = 'Sarah';

function myFunc(){
   //creates a new variable with name myName in the scope of myFunc. 
   // This is different from the global variable myName but hides it inside the function scope
   var myName = 'Jerry' 
   console.log(myName);
}
//As soon as function scope ends, the global variable myName becomes visible

myFunc(); // Writes 'Jerry' to console
console.log(myName); //Writes 'Sarah' to console
  • However, if same variable from outer scope is assigned a value in inner scope its value is overridden. Note that the only difference in previous example and this example is no use of var keyword inside function myFunc for variable myName.
var myName = 'Sarah'
function myFunc(){
   //changes the value of myName variable from outer scope
   myName = 'Jerry';
   console.log(myName);
}

cosnole.log(myName); //Writes 'Sarah' to console
myFunc(); // Writes 'Jerry' to console
console.log(myName); //Writes 'Jerry' to console
  • Let’s try a third somewhat strange scenario to understand the function scope really better. Below we are passing the variable from outer scope as argument to the function myFunc. Here, the argument is passed by value not by reference therefore, the value of variable from outer scope does not change
var myName = 'Sarah'

function myFunc(myName){
   console.log(myName); //Write 'Sarah' to console
   //changes the value of local variable myName which is different from the global one
   myName = 'Jerry';
   cosnole.log(myName); //Writes 'Jerry' to console
}
myFunc(myName); 
console.log(myName); //Writes 'Sarah' to console
  • BEWARE – If a variable is initialized inside function without first declaring it (using var keyword) it is tied to global scope not local variable.
myFunc(){
   myName = 'Sarah'
   console.log(myName) //Writes 'Sarah' to console
}

myFunc();
//As the variable myName was declared without using var it is tied to global scope and is also accessible from outside functopn
console.log(myName); //Writes 'Sarah' to console

The global scope in javascript is nothing but window object. It is important to limit the declaration of variables in global scope because, global variables can be accessed and modified from anywhere and hence they cannot be secured

  • Javascript function are variable tied to global scope. If a function is written directly inside script tag without a nesting it inside another function. It is tied to global scope
function myFunc(){
    console.log('This is my test function')
}

var myFuncVar = window['myFunc'];
myFuncVar(); //Calls the myFunc function from global scope which writes 'This is my test function' to console

After studying the variable scope closely, I came to realization that a solid understanding of Variable scope is not only necessary for me to write correct and concise code but also is essential to build a foundation of many advanced concepts in the JavaScript and also the design patterns.

I hope these points and code snippets would give you a high level idea as to how the variable scope works in JavaScript and a quick reference while coding.

THANKS!

References:

JavaScript Variable Scope and Hoisting Explained

MDN – var

 

Advertisements