Skip to main content

Command Palette

Search for a command to run...

Understanding Scope in Javascript

Published
•2 min read•View as Markdown
Understanding Scope in Javascript

What is Scope?

As its name would suggest Scope is the region or space where a variable can be accessed. It manages the availability of variables or we can also say that it specifies the accessibility of variables.

Different types of Scopes in JavaScript:

  • Block scope
  • Function scope
  • Local scope
  • Global scope

Block Scope -

This scope restricts the variable that is declared inside a specific block that is brackets {} from accessing it outside of that block.
The let and const keyword comes into the category of block scope, Hence they cannot be accessed outside of the block whereas var is globally scoped, it can be accessed anywhere no matter where it is declared.

{
   var first = 10;
   let second = 20;
   const third = 30;
}

console.log(first);  // 10
console.log(second);  // Uncaught ReferenceError: second is not defined
console.log(third);  // Uncaught ReferenceError: third is not defined

Function Scope -

This scope restricts the variables that are declared inside a function from accessing those outside of that respective function.

function myFunction() {
   var first = 10;
   let  second = 20; 
   const third = 30;    
   console.log(first);  //10
   console.log(second);  //20
   console.log(third);  //30
}

console.log(first);  // Uncaught ReferenceError: first is not defined
console.log(second);  // Uncaught ReferenceError: second is not defined
console.log(third);  // Uncaught ReferenceError: third is not defined

Local scope -

Variables that are declared inside a function become local to that function. These types of variables are created when the function starts and deleted when the function is executed.
Local variables have Function Scope which means that they can only be accessed from within the function.

function myFunction() {
    var first = 10;
    console.log(first);
}

myFunction()  //10
console.log(first);  // Uncaught ReferenceError: first is not defined

Global Scope -

The variables that are declared Globally (outside of any function) have Global Scope and these global variables can be accessed from anywhere in the program.

var first = 10;
let second = 20;
const third = 30;

{
  //first, second, third all three variables can be accessed here
}

console.log(first)  //10
console.log(second)  //20
console.log(third)  //30


function myFunction() {
    //first, second, third all three variables can be accessed here
    console.log(first);   //10
    console.log(second);   //20
    console.log(third);   //30
}

myFunction()

This was a short summary of the scope in JavaScript.
To Conclude Scope, scope defines where exactly variables can be accessed or referenced which is why it is a very important topic in JavaScript.