The following code will output "1." However, shouldn't the keyword "let" not make x a global variable, thus making it invisible to das()? let is supposed to limit the scope of variables to only the block where they're declared, yet here, I'm seeing an inner function have access to a "let" variable, even though x was declared outside its scope. How is that possible?
function letTest() {
function das () {
console.log(x);
// How does this function have access to a let variable declared outside its scope?
}
let x = 1;
das();
}
letTest();
Here's a way of thinking about how
let
works:let
.{
.let
find the corresponding}
.That gives you the scope wherein the variable will be visible. If a function definition appears in that scope, fine; the variable is visible to code in that function.
Now, what's a little bit weird is that in your example the variable looks like it's used in the scope before it's declared. That's where the fact that the reference appears before the declaration becomes a little more interesting.
Normally, if code in a scope refers to a
let
-declared variable before thelet
actually happens, that's an error. However, that's a runtime thing, not a syntax thing. In your case, at runtime thelet
will have "happened" by the time the nested function is called.