Introduction to local and global scope in JavaScript

Global Scope :

If a variable is under global scope, it is accessible in any files in the application. If you define a variable outside of all functions and curly braces {}, it will be moved to Global Scope.

var msg = 'Hello World'

function printMessage(){


In the above example, variable msg is in global scope. We can access it and modify it from anywhere. It will print the below output :

"Message :  Hello World"
"Message :  Hello Universe"

Defining a variable in global scope has a lot of problems. It may cause conflicts in your code. If you declare multiple global variables with var keyword, the second variable will overwrite the first one. Again, if you declare with let or const keyword, it will throw one error that the variable is already defined.

Local Scope :

Variables defined with local scope are not accessible globally. Their access is limited. We can’t access any local scoped variable from a different function. These variables are also called local variables.

function functionName(){
	//local scope

Local scope is categorized into two types :Function scope and block scope.

Function Scope:

As its name suggested, a function scope defines the visibility or scope inside a function. For example, take a look at the below function:

function printDetails() {
	let msg = "Hello World"



We have declared the variable msg inside the function functionOne. This variable can be accessed only inside the function functionOne. It can’t be accessed from anywhere outside of this function. Even if we declare another function in the same class, it can’t access that variable in functionOne.

If you run the above program, it will throw the below error for the second console.log :

ReferenceError: msg is not defined

Block Scope:

Anything inside curly braces or {} is a block and variables within that scope is called block scope. For example, switch cases, if cases, while loop, for loop etc. are all block scope.

You need to define a variable by using const or let to declare it in a block scope. const and let were introduced in ES6. If you declare a var, it will fall in functional scope.

For example :

function printDetails() {
  for (var i = 0; i < 1; i++) {
    let msgOne = i;
    var msgTwo = i + 1;

    console.log("msgOne inside loop :" + msgOne);
    console.log("msgTwo inside loop :" + msgTwo);

  console.log("msgTwo outside loop :" + msgTwo);
  console.log("msgOne outside loop :" + msgOne);


It will execute the console.log messages inside the loop without any issue since both let and var variables falls in a block scope. But it will print only msgTwo outside the loop, not msgOne. Because, msgOne is created using let which is only a block scope variable. If the program exits the for loop, it will exit the block scope and move into the functional scope.