Hoisting in Javascript
Look at the below code and guess its output:
console.log(val);
var val;
If you have not studied hoisting and if you are learning javascript after learning any other programming language like Java or C++ then your guess will be " that the above code will return an error".
But let me tell you it is wrong, the output of the above code will be "undefined". So let us the how hoisting works by getting started with our blog.
What is Hoisting?
Hoisting is a kind of process where the javascript interpreter moves the concept of declaring variables at the top of their scope before the code is executed.
Hoisting works with all var, let & const but the output is still different while using var and let/const for declarations.
Hoisting with var
Variables which are hoisted with the var keyword are initialized with the value "undefined". Therefore if you are to access particular variables without initializing them then it will return undefined.
console.log(value_check);
var value_check;
Hoisting with let & const
Variables which are hoisted with let & const keywords are hoisted but they cannot be accessed before initializing the value. Therefore it will give a "Reference Error" as output.
Code:
console.log(myval);
let myval;
Output:
ReferenceError: Cannot access 'myval' before initialization
We are getting "Reference Error" because the variables declared with let/const keywords are present in the Temporal DeadZone.
Hoisting for functions
We can hoist the functions as well in javascript as it helps the programmer to understand the main structure of the code. Understanding the structure before looking at the actual implementation can really help a programmer.
Code:
start();
continuous();
end();
function start(){
console.log("Performing some beginning operations");
}
function continuous(){
console.log("Performing continuous operations");
}
function end(){
console.log("Performing final operations");
}
Output:
Performing some beginning operations
Performing continuous operations
Performing final operations
I hope you were able to understand the concept of hoisting through this blog. Feel free to ask your doubts and share your thoughts in the comment box.