Before going further, a couple of lines on the basics
Compile code. Move declarations at the very top of scope and remember those declarations (this is also called ‘hoisting’). Even if the variable is initialized during declaration, the compiler does not assign values at this time.
When execution engine encounters variable assignment, it allocates memory and points variable to the memory location
With this in mind, let us rock and roll.
Any variable declared within a program but outside of a function is said to be global. Such variables can be accessed from anywhere within the program.
Any variable declared locally in a function will be accessible only within that function.
The same is true for a block.
You now see the pattern - while function or block has access to parent variables, child variables are not available to the parent.
You would also have noticed that I used
let. This will tie the variable to the parent block / function scope.
If I had used
var instead, we have slightly different result.
The above variable visibility behaviour should be the single biggest reason for you to switch from
let. The program throws an error for a variable that is not accessible rather than having a silent ‘undefined’, or showing the value that was supposed to be within a block.
The above example with
var also illustrates the definition of a ‘lexical scope’. Variable value gets defined by the position of the variable rather than the block.
letmoved variable declaration to beginning of the block at compile time
- Execution engine could not find any definition of
z function local 1and errored out
- Same is the case if variable is found after the parent block in which it is defined
varmoved variable declaraion to beginning of everything at compile time
- Execution engine could see the definition of
z function local 1, but not find any value. Returned undefined and continued
- Execution engine went through the block in which
zvalue was assigned
- Engine encounters
z function local 2and prints the value assigned within the block
const has the same behaviour as
To make variables in one module available to others, you have to explicitly export the variable.
These variables can then be used in other modules using an
- Define variables only when necessary. Make them local to a block / function and avoid global variables