Confusing Side of Javascript Scopes — Global Scope
In the last blog we learned about scopes in Javascript. If you haven’t checked the last blog , you can check here.
Today, I will share few use cases of — what happen when you write the JS programs and mix the global scopes and local scopes.
Case1 : What would be the output of console.log in below code snippet?
:
Explanation: At line #1 abc is defined as global variable and accessible throughout the program. At line #4 we are redeclaring the abc. Now, its scope is just limited to the function f only also due to the local scope new abc in function f() t is not able to touch the value of the abc global variable. Hence, at the line #10 we are still getting the global value.
Case 2 : What would be the output of console.log in below code snippet?
Answer:
Explanation: At line #4 we are only changing the value of abc global variable.We are not re-declaring the abc global variable. (we haven’t used the var keyword within the function f() due to that JS compiler is able to change the value of global variable - abc).
Case 3 : What would be the output of console.log in below code snippet?
Answer:
Explanation: This is the most simple as we are simply trying to access the global variable abc at #3 hence we got the value ‘global’. After this we changed the value and at #5, we got “I am from inner scope”. Now, the global variable — abc’s value is changed hence we got the #11 “I am from inner scope”.
Case 4 :What would be the output of #4 and #8?
Answer:
Explanation: This is the most interesting behaviour of the Javascript. As this particular example introduce a new concept — “Shadow Scoping”.
When you try to redeclare a variable in functional scope which is already declared at the global scope and you try to access it in functional scope it will throw you undefined. The functional scope will block the access to the global variable . This is why we are getting #4 undefined. At #6 abc has the access of the functional scope variable abc and it is giving -”I am from inner scope” . #11 abc — the global variable’s value is untouched. Hence we got the global value.
All examples are on codepen.
What will happen when you start merging the global with block level scopes?Do check the next blog.