Hoisting in Javascript
Hoisting is easy to understand but recently I have noticed certain amount of confusion around it. Yesterday I read a definition which stated, hoisting in javascript implies that variables and function declarations are physically moved to the top of the code; I was little confused because clearly this is not what happens in javascript hoisting.
Consider an example here:
var a = "Hello"; // simple variable declaration
function b(){
console.log("Inside function");
} // simple function declaration in es5 syntax
b();
console.log(a);
This is normally how we write code and it is the best practice too. But javascript can also perform certain unexpected things which you, normally, would not expect.
Now let us see the snippet again with a little tweak :
b();
console.log(a);
var a = "Hello"; // simple variable declaration
function b(){
console.log("Inside function");
} // simple function declaration in es5 syntax
In most programming languages you would get an error for something like this but javascript works differently.
The above code outputs something like this:
Inside function undefined
Javascript actually ran the function and didn’t throw an error. As a matter of fact, variable `a` was also available to it before execution.
Let us make some more changes and remove `
a
` altogether :b();
console.log(a);
function b(){
console.log("Inside function");
} // simple function declaration in es5 syntax
Now, we get an error in the console:
Uncaught ReferenceError : a is not defined
There is a major difference between “Not defined” and “Undefined”, perhaps discussion for another article. This example also does nullify the definition of hoisting which we discussed earlier, because if it were the case,
a
would not have been undefined, instead it should have been Hello
.
So why does this happen, why does Javascript works the way it does?
The reason why javascript works this way is because of its execution context.
Execution context is created in two phases:
- Creation Phase
- Execution Phase
The first phase is called the creation phase. In this phase the parser runs through the code and recognises your variable & function declarations and sets up memory space for them. The variables and functions actually persist in the memory before the code executes line by line.
However, variables differ from functions in this context. The functions are stored in the memory in their entirety, with the name and code inside their scope, but for variables, assignment takes place in the execution phase so when javascript engine sets up memory space for
a
, it does not know its value, hence the undefined
.
Even though hoisting technically kind of works, you can get into a lot of javascript pitfalls if you rely on it too much. Hence we should avoid depending on hoisting for best results.
Comments
Post a Comment