Variable Scope in JavaScript
- Local Scope in JS:
When a variable is declared inside any block of code, it will be called a Local variable. It will only be available within the block where it is declared and is not accessible in other blocks. A local variable is declared by var, let and const keywords.
- Global Scope in JS:
Similar to the Local scope variable, it is also declared by var, let and const keywords. When a variable is declared in the outermost blocks of code, it will be called a Global variable. It will be available within any block.
let a= " i am global variable"
if (true){
let b="i am local variable" // it will be available only inside this if block
console.log(a) //no error
}
console.log(b) // ReferenceError- undefined variable
Lexical environment:
In JS, every block or function of code will have its internal object called a Lexical environment. It consists of two parts Environmental records (it will store all the variable properties and values declared inside the block) and Reference to the outer lexical environment (it connects to the next lexical environment).
whenever a new variable is created inside a block, the variable becomes the property of environmental records. When JS engine started to read the code, it will first check the innermost block's lexical environment. If a variable is used inside an inner block but not declared, then the engine will check in the next environment likewise it will finally check the global lexical environment (outermost). If a variable is declared in any block, then it will raise the undefined variable error.
let a= " i am global variable"
//global lexical environment
if (true){
//local lexical environment
let b="i am local variable"
console.log(a) //engine will check the outer environment for this
}
console.log(b) // engine will check the next outer environment for this. Due to no next environment, it will raise ReferenceError- undefined variable