Skip to main content
0:01est. 4 min

Lesson 10- The Execution Context (Creation and Hoisting)

Notes

Example 1
var a = "hello";
function b() {
console.log("called b!");
}
b(); //called b!
console.log(a); // hello

-----------------------------------------------------------------------------------

Example 2 (Moving function calls on top)
b(); //called b!
console.log(a); //undefined {This phenomenon is called Hoisting}
var a = "hello";
function b(){
console.log("called b!");
}

In most of the programming languages you will get an exception. Because programming languages execute their code line by line and since we haven't gotten to the function b, i can't use it yet. That's what we normally expect.
But in javascript it ran the function and instead of throwing an error it gave me a value - undefined. So even though the function was below but got executed

-----------------------------------------------------------------------------------

Example 3 (Remove variable)
console.log(a); //Error : a is not defined

-----------------------------------------------------------------------------------
As per web, Hoisting - Functions in javascript are moved to the top by the js engine.As if the are physically moved to the top. So that they work, no matter where you put them. But variables are also declared not initialized.

Actually -
Execution context is created in two phases.
The first phase is called Creation Phase.
In this phase we know js engine creates global object ‘this' in memory, outer environment is also created and in that creation phase as the parser runs through your code. It recognizes where you have created the variables and where you have created functions.
So it setup memory space for variables and functions and it's that step that is somewhat confusingly called Hoisting. It's not actually moving code to the top of the page.

Before your code is executed line by line the js engine set aside a memory space for the variables in entire code and all of the functions you have created. So those variables and functions exists in memory. So when the code begin to execute line by line it can access them, however when it comes to variables it's different.

Function is entirely placed into the memory space but the assignments of variables are set in next phase Execution Phase. So when js engine setups memory space for "a" it doesn't know it's value unit it being starts executing this code. It puts a placeholder "undefined". All variables in js are initially set to undefined and functions are setting in memory in their entirety

That's why it's a bad idea to rely on hoisting in any way.