What is Scope?
Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript.
Types of Scope in Javascript:
Module Scope
Function Scope
Block Scope
Lexical Scope
Global Scope
Module Scope
In a module, when a variable is declared, it is hidden and not available to other modules unless it's exported.
Function Scope
Variables and Parameters declared inside a function are accessible inside the function but not outside the function.
Block Scope
Block Scope is defined with curly braces. It is separated by { }. Variables declared with let and const can have block scope. They can only be accessed in the block in which they are defined.
The flowing loop code displays the number 5, five times.
(function run(){
for(var i=0; i<5; i++){
setTimeout(function logValue(){
console.log(i); //5
}, 100);
}
})();
The for loop statement, with the let declaration, creates a new variable locale to the block scope, for each iteration. The next loop code shows 0 1 2 3 4 5.
(function run(){
for(let i=0; i<5; i++){
setTimeout(function log(){
console.log(i); //0 1 2 3 4
}, 100);
}
})();
Lexical Scope
Lexical Scope means that in a nested group (function within a function) of a function, the inner functions have access to the variables and other resources of their parent scope.
N.B: Here access means to read and write access.
Global Scope
Variables defined outside any function, block, or module scope have global scope. Variables in the global scope can be accessed from everywhere on the application.
Scope Chain:
When a variable is used in JavaScript, the JavaScript engine will try to find the variable’s value in the current scope. If it could not find the variable, it will look into the outer scope and will continue to do so until it finds the variable or reaches the global scope.
If it still could not find the variable, it will either implicitly declare the variable in the global scope (if not in strict mode) or return an error.
let foo = 'foo';
function bar() {
let baz = 'baz';
console.log(baz); // Prints 'baz'
console.log(foo); // Prints 'foo'
number = 42;
console.log(number); // Prints 42
}
bar();