Hoisting
Creation and Hoisting
People say variable and functions are moved to the top, but not quite right.
Example:
var a = 'Hello World!';
function b() {
console.log('Called b!');
}
b(); -> 'Call b!'
console.log(a); 'Hello World'
b(); -> 'Call b!'
console.log(a); -> 'undefined'
var a = 'Hello World!';
function b() {
console.log('Called b!');
}
Most programming language it will throw an error, as it execute the code one lines at a time and we did not execute the b function yet.
But Javascript is not like that:
Instead of throwing an error:
On Chrome Dev Console:
"Called b!"
'undefined' - This is called Hosting
What is really happening:
The execution context is created in two phases:
Creation Phase
Before your code your code is run, the Javascript engine has already setup memory space for variables and function.
When it comes to variable, it is a bit different. Function entirely is placed in the memory place but the next phase (Execution Phase - execute code line by line) thats when assignments are set (eg: var a = 'Hello world').
So when the JS Engine is setting up memory space for var a, it does not know its value until it become executing its code. So it placeholder called 'undefined'.
All variable in JS are initially set to 'undefined'