Why? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why?

If the function is executed outside the block scope, why can it find the variable? https://code.sololearn.com/Wa3nFlsWRoMI/?ref=app

7th Dec 2020, 6:05 PM
Karak10
Karak10 - avatar
9 Answers
+ 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.
8th Dec 2020, 7:14 AM
David Carroll
David Carroll - avatar
+ 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
7th Dec 2020, 6:10 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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.
7th Dec 2020, 6:18 PM
A͢J
A͢J - avatar
+ 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.
7th Dec 2020, 6:22 PM
Karak10
Karak10 - avatar
+ 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.
8th Dec 2020, 3:58 AM
Ore
Ore - avatar
0
Царь СОБАКА - Догго I why does it work when I call the function if the function is called outside the code block?
7th Dec 2020, 6:08 PM
Karak10
Karak10 - avatar
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.
7th Dec 2020, 6:10 PM
A͢J
A͢J - avatar
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.
7th Dec 2020, 6:13 PM
Karak10
Karak10 - avatar
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.
7th Dec 2020, 6:14 PM
Karak10
Karak10 - avatar