The scope manages the accessibility of variables.
The Scope decides how far the JavaScript will go to look ๐ง for a variable. In the event that it's doesn't exist in the current extension, ๐คช it'll look ๐ in the external Scope .
Scope in JavaScript is the area where we have ๐ Correct โ access to a variable / function.
kinds of scopes in JavaScript โ
๐๐ฅ๐จ๐๐ค ๐๐๐จ๐ฉ๐{...} :- ๐ฏ
Block scoped variables are only accessible inside a block brackets. Which can be, inside an if block({....}), function-block, loop(for,while...), or an seperately defined block. Anything in between by curly braces is a block.
A code block in JavaScript defines a scope for variable declare using let / const as-
if (true) {
// "if" block scope
const message = 'Aayu';
console.log(message); // 'Aayu'
}
console.log(message); // throws ReferenceError
Standalone code blocks. The standalone code blocks also creates a scope:
{
// block scope
Let message = 'Aayush';
console.log(message); // 'Aayush'
}
console.log(message); // throws ReferenceError
Note: var is not block scoped
๐ ๐ฎ๐ง๐๐ญ๐ข๐จ๐ง ๐ฌ๐๐จ๐ฉ๐ ๐(){.....}, ๐ฅ
Variables Scoped inside a function are only available inside a function.
function walk() {
// "Walk" function scope
var message = 'Walk, fast, walk!';
console.log(message); // 'Walk, fast, walk!'
}
Walk();
console.log(message); // throws Reference Error
๐๐ฅ๐จ๐๐๐ฅ ๐ฌ๐๐จ๐ฉ๐ |......| :-
The Variables / functions Which have global scope can be accessed everywhere in the Code-Block or module file.
A variable announced inside the worldwide extension is named worldwide variable. Worldwide factors are available from any extension.
Lexical scope
A lexical scope Contains outer scopes declared constantly.
Letโs define 2 functions, having the function inner() is nested inside outer().
function outer() {
// the outer scope
let outerVar = 'I am from outside!';
function inner() {
// the inner scope
console.log(outerVar); // 'I am from outside!'
}
return inner;
}
const inner = outer();
inner();
Top comments (2)
Hello @aayushjaincode !
Uses block code for better post like this :
Editor guide
thanks for improvements