DEV Community

Ramya Sri M
Ramya Sri M

Posted on

Scope in JavaScript

In JavaScript, Scope defines how variables are accessed and managed throughout the program. There are three types of scope:

  • Global Scope
  • Local Scope
  • Block Scope.

Global Scope

Global scope is defined by variables that are declared outside of any function and can be accessed anywhere in the program.



var gVar = "Global Scope";
function globalScope(){
   console.log(gVar)
}
globalScope()
console.log(gVar)


Enter fullscreen mode Exit fullscreen mode

Output

Global Scope

Local Scope

Local scope is defined by variables that are declared inside a function and can be accessed only within that function.



function localScope(){
   var lVar = "Local Scope";
   console.log(lVar)
}

localScope()
console.log(lVar)


Enter fullscreen mode Exit fullscreen mode

Output

Local Scope

Block Scope

Before ES6, JavaScript had only two types of scope: global scope and local scope. After ES6, two new keywords, let and const, were introduced. These keywords provide block scope in JavaScript. A block is defined by { } and variables declared inside a block can only be accessed within that block.



function blockScope(){
   let blockVar = "Block Scope";
   console.log(blockVar);
}
blockScope()
console.log(blockVar);


Enter fullscreen mode Exit fullscreen mode

Output

Block Scope

I hope this explanation clarifies the concept. If you have any questions or corrections, feel free to ask in the comments.

Top comments (0)