DEV Community

loading...
Cover image for Beginners guide to Hoisting in Javascript

Beginners guide to Hoisting in Javascript

a_shokn profile image Ashok Naik ・1 min read

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"
*/

Enter fullscreen mode Exit fullscreen mode

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"
*/
Enter fullscreen mode Exit fullscreen mode

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
*/
Enter fullscreen mode Exit fullscreen mode

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.

Discussion (2)

Collapse
jonrandy profile image
Jon Randy

They're not moved to the top at all, that's just a convenient mental model to easily understand how the code will behave

Collapse
ms_yogii profile image
Yogini Bende

The second case will also be valid for arrow functions. It would be great if you add that as well. Great article though 🙌

Forem Open with the Forem app