MV [RMMZ] Variable Scopes

I wanted to ask you guys how the scope of variables work in Javascript to learn how they get affected depending on the place they are declared.

In Ruby I know that a local variable can be used inside any method and need to be passed to another method as an argument.
The same happens in C, C++ and Javascript. No problems here.

Yet, what happens if a let variable is defined inside a conditional statement?
Can we call it after the condition has been executed without getting an error message?

In Ruby that would work fine because it doesn't enforce any specific rule about local variables, but it wouldn't work in C and C++ at all. I'd need to define it outside that statement.

What about Javascript?
In JavaScript, let has block scope.

Yet, what happens if a let variable is defined inside a conditional statement?
You get a syntax error, you can't define a variable inside a conditional.

If you declare it inside a loop, it will be inaccessible outside of that loop.
Screenshot 2023-02-03 145707.jpg
If a let variable is declared inside a conditional statement code block, then it can only be referenced from inside that same code block. I actually wrote a pretty detailed explanation about variable scope (with examples) the other day. If you're interested in learning more about it, you can find that post here.

*edit* Oops, I may have misunderstood your question. I thought you meant within a code block that is tied to a conditional statement. Can you give an example of why you would ever benefit from trying to define a variable from within a conditional statement itself?
Oh, when you said "in a conditional statement" did you mean in the resulting code (block)? My understanding of the terminology is the if (this part here) is the conditional statement.

But, regardless, it's still limited in scope to that code block, as the link and Arthran says, and my screenshot shows 🙂
If you want to dive deeper here are links to the for-statement specification (ES6)

How scoping works seems to be here:

For some practical examples try testing var and let.
JavaScript:
// Let
for (let i = 0; i < 4; i++) {
    console.log(i)
}
console.log(i)

// Var
for (var i = 0; i < 4; i++) {
    console.log(i)
}
console.log(i)
Thread closed

Original thread: https://forums.rpgmakerweb.com/threads/rmmz-variable-scopes.154658/