Scope
1. Scope defines the visibility or accessibility of a variable.
We Have Two Scopes
1. Global Scope
2. Local Scope
Global Scope
1. The variable declared in the global scope can be accessed anywhere in the program.
2. Global scope has the highest accessibility.
3. Variables declared with var go in the global scope.
Local Scope
1. Local/Block Scope/Function Scope
2. The variable declared in the local scope can be accessed in that block only, i.e., we cannot access the variable from outside.
3. The JS engine creates local scope for functions and blocks.
Function's Local Scope
- Local scope created for a function is referred to as function scope.
- Variables declared in the function's scope cannot be accessed from outside.
Block's Local Scope
- Local scope created for a block is referred to as block scope.
- Variables declared in block scope cannot be accessed from outside.
- But only variables declared with var are accessible from outside the block.
Note: Variables declared with let and const are also locally scoped.
- Firefox represents it as Block Scope.
- Chrome represents it as Script Scope.