Hoisting in Javascript
Table of contents
What is Hoisting in JS?
Hoisting in Javascript is a behavior in which a function or variable can be used before declaration. It is the default behavior of javascript to move declarations to the top.
Variable Hoisting
Regarding variables and constants, keyword var is hoisted, and let and const do not allow hoisting.
a= 8;
console.log(a);
var a; // 8
Above, Variable a is used before declaring it And the program displays the output 8.
If a Variable is used with the let keyword, that variable is not hoisted.
a= 8;
console.log(a);
let a; // error
Function Hoisting
A function can be called before declaring it.
fun();
function fun() {
console.log('Hello World');
}
Above, the function fun
is called before declaring it and the program shows the output. This is due to hoisting. The declaration of the function message is moved to the top of the JavaScript file. This means that actually, the function call is made after the declaration and not before it.
Conclusion
Hoisting is JavaScript's default behavior of moving declarations to the top. Declare all of your variables at the top of their scope (at the top of the global scope or at the top of the function scope). Make sure you put all your functions, if you can, also at the top of their scope.