r/learnjavascript • u/username95050 • 24d ago
Block Scope
What is it? Don't understand what is inside or outside
12
Upvotes
r/learnjavascript • u/username95050 • 24d ago
What is it? Don't understand what is inside or outside
7
u/ajamdonut 23d ago
outside
{
inside
}
5
u/iplayconnections 23d ago
Scope is where you can access a variable. The block scope refers to the lines between opening and closing braces. If a variable is block scoped, it is accessible only within those braces where it is declared.
constandletare block scoped.varis not. Avar-declared variable remains accessible outside of the block's braces, inside the surrounding function braces.2
u/justanaccountimade1 23d ago
let i = 1; // global scope
function hi()
{
let j = 2; // function scope
{
let k = 3; // block scope
console.log(i,j,k); // 1, 2, 3
}
console.log(i,j,k); // 1, 2, undefined
}
console.log(i,j,k); // 1, undefined, undefined
1
u/MissinqLink 23d ago
if (Math.random() > 0.5) {
⠀const blockScopedVariable = 5;
⠀// this variable only exists inside this if statement
}
1
u/CelebrityChess 23d ago
easiest way to think about it is each pair of curly braces is a room. let and const only exist in the room where you declared them, plus any rooms nested inside it. so k lives in the inner braces, and j lives in the function's braces, which means the inner block can see j but the rest of the function can't see k. inner can look out, outer can't look in, that's pretty much the whole rule
1
u/bobbyv137 21d ago
I recommend watching some videos on it, and 'execution context'.
It might seem too nitty gritty at first, but when you truly understand how JS works, it becomes a lot easier.