r/learnjavascript • u/username95050 • 3d ago
Block Scope
What is it? Don't understand what is inside or outside
4
u/iplayconnections 3d 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.
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.
1
u/CelebrityChess 2d 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 1d 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.
1
u/justanaccountimade1 3d 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
6
u/ajamdonut 3d ago
outside
{
inside
}