DEV Community

Cover image for Scopes and Hoisting in JavaScript
Aayush Jain
Aayush Jain

Posted on • Edited on

Scopes and Hoisting in JavaScript

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();


Hopefully, my post has helped you understand the scope better!

Top comments (2)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello @aayushjaincode !

Uses block code for better post like this :

console.log()
Enter fullscreen mode Exit fullscreen mode

Preview code block

Editor guide

Collapse
 
aayushjaincode profile image
Aayush Jain

thanks for improvements