What is the scope of variables in JavaScript?


Scope means where we can access variables, functions or objects in part of code dynamically. Dynamically means during run time. The scope is the basic important concept in javascript to know the visibility of variables or functions. There are two types of scopes: Local and global scope.

Global Scope

Any variable which is declared outside any function defines the global scope. We can access the global variable anywhere in our code. There is one global scope throughout the javascript code.

var a = "Hello"; // Be default this variable has global scope

We can access the global variable inside the function also shown below:

var a = "Hello World";

function setVar(){
  console.log(a);  //Prints Hello World on the console as variable a has global scope

Local Scope or Functional Scope

Variables that are declared inside a function has local scope. Every function has its own local scope means if the same variable name is declared in two functions, then it is treated as two different variables as every function has its own defined local scope. We can't access variables from another function.

var a = "Hello World";

function logFn(){
 // Local scope for logFn
 var a = 3;


function log(){
 // Local scope for log
 var a = 6;

console.log(a); // Global scope

The output will be as follows:

'Hello World'

Block Scope

Block statements such as if, else and switch conditions or any loops such as while, for, do-while don't create any new scope. Variables that are defined using var keyword have the same global scope within any block. 

   var a = "Hi";
   console.log(a); // prints 'Hi'

  console.log(a); // prints 'Hi' as var a has global scope

let and const 

We can declare local scope inside a block using let and const keyword. They define local scope inside the block. We can't access them outside the block statement. If we declare using the var keyword inside the block, we can access that variable outside the block. 

  let a = 4;
console.log(a) // error: Uncaught ReferenceError: a is not defined

Now we will see an example using var, let and const.

  var a = "hello";
  let b = "let" ;
  const c = "bye";

  console.log(a); // Has global scope
  console.log(b); // Has block scope
  console.log(c); // Has block scope

The output will be as follows.

error: Uncaught ReferenceError: b is not defined