DEV Community

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

Posted on • Updated 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