JavaScript execution context and hoisting

Execution Context and Hositing

Lets take the test.js file and modify it with the following var a = 'hello world!'; function abc(){ /* will print in js console */ console.log('called abc'); } abc(); console.log(a);

Load index.html and check js console in developer tool.

called abc
index.html:12 hello world!

Now lets move abc() and console.log(a) at the top; in many programming language this would throw exception, but not in javascript. Lets see what we get in console.

abc(); console.log(a); var a = 'hello world!'; function abc(){ /* will print in js console */ console.log('called abc'); }

check js console in developer tool.

called abc
undefined

Even though a declared before it defined javascript doesn't throw any error but at the point in console it shows as undefined.
Now if we remove var a = 'hello world!'; then we get an error in the console.



abc(); console.log(a); function abc(){ /* will print in js console */ console.log('called abc'); }

check js console in developer tool.

called abc
Uncaught ReferenceError: a is not defined


This above phenomenon is called hoisting.
Lets go little deeper, the way things worked it may seem to us javascript engine hoisting all the variable/function so that they find references during execution, kind of the code has been rewritten like below.

function abc(){ /* will print in js console */ console.log('called abc'); } var a; abc(); console.log(a); a = 'hello world!';
In reality what executed is not actually what's written; it's translated by javascript engine.

Actually javascript engine doesn't physically moving part of code up and down to make thing work.
Let's dig little deeper on this.

Cinque Terre

At the beginning of execution context creation; global object, this which refers to global context and outer environment gets created. In this creation phase when parser runs through code it recognizes variable and function. It setup memory space for variable and function which is known as 'Hositing'.
So those function and variable exists in memory as part of initial phase of execution context creation which happens even before code starts executing.
Now function entirely place in the memory, that means function and its whole code inside, but thats not same for the variable. For variable it puts a space holder which is 'undefined'. The same space holder will be assigned if we do not set any value.

var a; function b(){ console.log('I'm in the function); } Cinque Terre
Back Next