Hoisting is one of the most commonly asked concepts in a Javascript interview. In this blog, we’ll find out how the hoisting mechanism occurs in JavaScript.
Hoisting is a mechanism in which variable and function declarations are physically moved to the top of your code(hoisted).
let's go through a simple example to understand hoisting
function blogName(name) {
console.log("Title of the blog is " + Hoisting);
}
blogName("Hoisting");
/*
The result of the code above is: "Title of the blog is Hoisting"
*/
The above example is how we expect the code to work without any issues. A function declaration followed by the call to the function.
let's take another example where we call the function before we declare it
blogName("Hoisting");
function blogName(name) {
console.log("Title of the blog is " + Hoisting);
}
/*
The result of the code above is: "Title of the blog is Hoisting"
*/
In the above example gives us the same output even though the function is called before declartion. This is because the function blogName()
was hoisted to the top.
Note: JavaScript only hoists declarations, not initialization
blogName("Hoisting");
var blogName = function(name) {
console.log("Title of the blog is " + Hoisting);
}
/*
The result of the code will be Uncaught TypeError: blogName is not a function
*/
All you need to know Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
That's All folks, Thank you.
Top comments (2)
They're not moved to the top at all, that's just a convenient mental model to easily understand how the code will behave
The second case will also be valid for arrow functions. It would be great if you add that as well. Great article though 🙌