r/learnjavascript • u/username95050 • Oct 23 '26
Block Scope
What is it? Don't understand what is inside or outside
5
u/iplayconnections Oct 23 '26
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.
const and let are block scoped. var is not. A var-declared variable remains accessible outside of the block's braces, inside the surrounding function braces.
2
u/justanaccountimade1 Oct 23 '26
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
4
u/naltous Oct 23 '26
those last two console logs are actually gonna throw a ReferenceError instead of printing undefined since k and j aren't declared in those scopes at all
1
u/CelebrityChess Oct 24 '26
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 Oct 26 '26
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.
2
u/JGhostThing 28d ago
And the rules for block scope work very similarly in all c-like languages. C, Java, C++, Rust, etc.
7
u/ajamdonut Oct 23 '26
outside
{
inside
}