Confusing Side of Javascript Scopes — Block + Global Scopes — Part 2
What happen when you start writing program and have JS scopes? Many times due to unmanaged scopes the output your get is totally unexpected?
No sweat, this is my 3rd post of the series of scopes. Here I will show you the use-cases of what happen when Globe and block scopes merge or conflict.
Confusing Sides of JS Scopes -Part 1
Case 1: Global Scope to Block Scope
Explanation: This is the code which narrate the journey of a variable through — Global, functional and block level. When this programs execute , at Line no #13 — we are able to access the global value of the abc as the abc is in global scope. Within function f(), we changed the value of abc at line #4 (Please note we are just changing the value and not declaring it). Hence, at line #7 we are able to access the functional scope value of abc. At line #8, we again changed the value of abc at block level but as we are just changing the value but at line #10 we still have the access to the block level value hence new.
Case 2: Global + Block Scope
Explanation: This example narrates what happen when you have a variable at Global scope and you try to re-declare it at block level. Line #13 will execute before f(). This time the only value of abc at the memory is only global. Hence, we got global output. Once the f() executed , at line no 4 we changed the value of abc to inner at functional scope. Now, memory changed the abc value to inner. At line 7 , we are trying to access the abc value but it will throw undefined reason is shadow scoping again — check this
Case 3: Global + Local Scope
Explanation : This is the most simple use-case. Where we are just changing global variable at functional scope and then declaring a new variable at block level with let. So, at line #7 we are able to access the functional level value which is “Inner” . At line no #8 we introduced block level local and its scope is only till the if block . Hence, we got undefined at #10
Code is at Codepen
Thank you for reading till the end. Loved it ? Do clap for it.
Follow me : twitter.com/hellonehha