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 four types of scope:

  • Global Scope
  • Local Scope
  • Block Scope
  • Module 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

Module Scope

Module scope was officially introduced in JavaScript with ES6. In ES6, each module has its own scope, meaning variables and functions inside a module are private unless explicitly exported. This version introduced the import and export keywords, allowing modules to communicate with each other.

  • Export: Allows you to share variables, functions, or classes from a module.
  • Import: Allows you to bring in variables, functions, or classes from another module.

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

Top comments (2)

Collapse
 
jonrandy profile image
Jon Randy 🎖

There are actually four types of scope. You missed Module scope.

Collapse
 
ramya_srim profile image
Ramya Sri M

You're right, thank you for pointing that out! I'll make sure to update it.