My Image My Image

Ask me anything

Explain the concept of hoisting in JavaScript?

Preffered Answer:

Hosting means we can use a variable even before declaring it. When the compiler RUNS(details in Question 1) and finds all the var declaration, it MOVE them to the top of the file.

Let’s consider this below example. Here we are assigning values to  on name , age and profession without declaring them first. They are declared on line 8, 9, 10 and yet the interpreter doesn’t throws a runtime error. It is because it doesn’t matter where the VARIABLES are declared. They are always hoisted to the top by when the compiler makes the first pass.

name = "Thomas"; age = 45; profession = "Engineering Manager";   console.log(`${name} aged ${age} is ${profession}`); //Thomas aged 45 is Engineering Manager   var name; var age; var profession;

This is also true for function declaration, as the compiler also treats function declaration as variable declaration as in JS all function declaration are object declaration. But same is not true for function expression and it will give reference error. 

console.log(funcDeclaration()); //Function declaration console.log(funcExpression());  //ReferenceError   function funcDeclaration() {   console.log('Function declaration'); }   let funcExpression = function() {   console.log('Function expression'); } /*

Exception: ReferenceError: can't access lexical declaration `funcExpression' before initialization



But why did we got this Reference error in function expression call. This is to do with the compiler and interpreter step in JavaScript, which we UNDERSTOOD in Question 1.
The compiler runs first and finds all the “var” , and the function declaration are also treated as variable declaration because in JS all function declaration are object declaration.
So, the function declaration call doesn’t give as any error.

But the same is not true about function expressions. Here when the compiler runs it registers a variable functionExpression at line 8, but it doesn’t knows what it is. So, when the interpreter runs at line 2, it throws a runtime error, because it doesn’t know what is functionExpression.

Write Your Comments or Explanations to Help Others