1 2 3 4 5 6 7 8 |
var a = 'Hello World!'; function b() { console.log('Called b!'); } b(); console.log(a); |
output:
Called b!
Hello World!
Now lets hoist our execution to the top.
1 2 3 4 5 6 7 8 |
b(); console.log(a); var a = 'Hello World!'; function b() { console.log('Called b!'); } |
output
Called b!
undefined
Now try removing the a
1 2 3 4 5 6 |
b(); console.log(a); function b() { console.log('Called b!'); } |
Now, you’ll get an error saying ‘a’ is not defined.
Reason – 5:00
Execution Context:
(1st) Creation Phase (global obj, this) – it sets up memory space for created variables and functions. This step is called Hoisting.
It’s not moving code on top of page. All it means is that before your code is being executed, the compiler has parsed your code, and those variables and functions already exist in memory. During execution, they exist and we can access them.
The function in its entirety (including its name) is placed into memory space.
(2nd) Execution Phase – However, in the next phase of executing your code, when it comes to variables, because it does not know ultimately what the values will be until it starts executing your code, will instead put a placeholder called undefined. It just means we don’t know what the value will be.
Hence, all javascript variables initially are set to undefined