0
Why?
If the function is executed outside the block scope, why can it find the variable? https://code.sololearn.com/Wa3nFlsWRoMI/?ref=app
13 ответов
+ 3
This is known as lexical scoping.
Lexical scoping involves statically binding a function to the variables in its outer scope.
Therefore, the block scoped variable `i` is statically bound to the function called `example`, regardless of where that function is called.
Think of the `if` block as a blueprint for defining the lexical scope (outer scope) to the inner function.
+ 1
Karak10 , because the variable is limited to the block. You can find more info about the difference between var and let here: https://www.w3schools.com/JS/js_let.asp
+ 1
Karak10 because inside the if block for the function example, i will behave like a global variable because both the function and i are within the same scope.
+ 1
I just thought calling a function meant it would run the code inside the function at the place I called the function, I didn't know it runs the code inside the code block it originally was made in.
+ 1
Scope changes when you call a function. The program enters the function(example) scope until the function has completely executed.
i is available throughout the if block which includes the closure function. So in the scope of example, i exists.
It does not work the other way around.
if (true) {
let i = 'test';
example();
}
function example() {
document.write(i);
}
Note: if var was used instead of let in any of these examples, there will be no error because they(i and example) will both be in the same scope.
0
Царь СОБАКА - Догго I why does it work when I call the function if the function is called outside the code block?
0
Karak10
let is used for scope variable means it will work within only the scope.
You can't access outside the scope. You can try var.
0
Царь СОБАКА - Догго I but the variable is, and the function which is called outside the code block uses that variable from outside the code block even though the variable is made using let keyword and is inside the code block.
0
AJ #Learn With Me 👨💻 that's not what I asked, I asked why the function example() which I called outside the code block can find the variety i. I already know why document.write(i) doesn't work.