Scope
The scope can be defined as the region in which a variable can be accessed. Outside this region, that variable is not available. In JavaScript, there are three types of scopes
- Block Scope,
- Function Scope,
- Global Scope
Block Scope -
Block scope is the scope between two brackets { },
{
let x = 10;
}
// x cannot be accessed here.
Function Scope -
Each function creates a new scope on its own called function scope.
function minimize(){
let x = 10;
//x can be accessed here
}
// x cannot be accessed here
Global Scope -
Variables declared Globally (outside any function) have Global Scope.
let x = 2;
var a = 3;
const b = 1;
{
// x, a, b all three can be accessed here
}
function print(){
console.log("This is a function");
// x, a, b all three can be accessed here
}
Scope of var, let, and const
Var is globally scoped, it can be accessed anywhere no matter where it is declared.
{
var a = 10;
}
console.log(a); //output will be 10
Let and Const are block-scoped, they can be accessed only inside the block they are declared in.
{
let a = 10;
const b = 20;
console.log(a, b); // output will be 10,20
}
console.log(a, b); //error
Output-
Conclusion -
This was a short summary on scope in JavaScript, you can learn more about scopes in MDN docs. Scopes help to understand the variable shadowing. I will be explaining shadowing in my next blog.