Javascript

What is Hoisting in Javascript?

In this tutorial, we will try to understand what is hoisting in javascript with some examples and demos. We will also try to understand what is the application of javascript hoisting in our programming.

In very simple words, Javascript Hoisting is a scenario or condition when the JavaScript interpreter moves all variable and function declarations to the top of the current scope. Let’s understand more about Hoisting in Javascript in detail.

Javascript Hoisting

What is Hoisting in Javascript?

As we already said, Hoisting is the default behavior in javascript by which id moves all the declarations at the top of the scope before code execution.

This allows us to use a function above its declarations as all the variables are moved to the top of their scope regardless of whether their scope is global or local. It’s important to keep in mind that only the actual declarations are hoisted and that assignments are left where they are.

Here is a small example explains the same.

console.log(num); 
var num;
num = 6;
// this will return undefined as Hoisting only hoist declarations.

However, this will work as Hoisting moves the declarations to the top.

num = 6;
console.log(num);
var num;
// return 6

How Hoisting works in Javascript?

JavaScript treats every variable which will be declared later on in a function differently than variables that are not declared at all. Basically, the JavaScript interpreter “looks ahead” to find all the variable declarations and “hoists” them to the top of the function.

We can understand this with the help of this given code snippets.

var declaredLater;

// Outputs: undefined
console.log(declaredLater);

declaredLater = "Now it's defined!";

// Outputs: "Now it's defined!"
console.log(declaredLater);

Here is a video explaining Hoisting in Javascript in more details

And that is how variable and function hoisting works in JavaScript. If you like this article feel free to share it with your developer friends and comment down if you got any suggestions. Again, Thanks for reading!

Leave a Comment