Whereas most of the time we are following a tutorial or a book that begins with Variables and Loops, there are certain aspects which end up being memorised than understood.
There are three basic fundamental concepts that we need to understand in order to get the real idea about JS underlying behaviour.
Lexical Environment and
Let's begin by understanding Syntax parsers:
Based on that actions of throwing an error or allowing the code to run is actioned.
This refers to where something in your code (be it variable or functions etc.) sits physically. To make it clear, in JS it matters where you put your functions and variables. Although this precedence is not something required for us to concentrate while understanding Lexical Environment, but we should just keep this is mind, for certain languages it matters where you put your code.
It is okay if you do not understand this, it took me quite a time to wrap this around my head as well. Let’s understand with an example.
Picture 1 illustrates how the execution context is being stacked on top of each other but keep this in mind JS will not run Execution Context 1 in this case until its finished with Execution context 2.
Now let’s go back to your code again. What we see is now we have a variable named “d” inside function “b()”, at this point JS will halt “execution context 2" and will create another execution context for “var d”.
Re-read this article if you have to. Comment if more explanation is needed but in order to proceed further on this topic we need to understand this very well.
Postscript: These concepts are taken from an amazing tutorial on Udemy. You can give it a shot (trust my words it is worth every penny). If not, I will surely be posting important concepts in my continuation of this series. I am trying to put in concepts that not every 300-page book will be explaining to you.
Let me know your feedback in comments below.