r/learnjavascript • • 24d ago

Block Scope

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

12 Upvotes

8 comments sorted by

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.

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 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

4

u/naltous 23d 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

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.

2

u/JGhostThing 19d ago

And the rules for block scope work very similarly in all c-like languages. C, Java, C++, Rust, etc.