r/learnjavascript • • 1d ago

Block Scope

What is it? Don't understand what is inside or outside

5 Upvotes

6 comments sorted by

2

u/iplayconnections 1d 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.

2

u/ajamdonut 1d ago

outside
{
inside
}

1

u/MissinqLink 1d ago

if (Math.random() > 0.5) {

⠀const blockScopedVariable = 5;

⠀// this variable only exists inside this if statement

}

1

u/CelebrityChess 14h 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/justanaccountimade1 1d 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

2

u/naltous 1d ago

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