Hoisting in JavaScript

An Awesome feature of JavaScript that is only available in JavaScript

·

2 min read

Hoisting in JavaScript

While learning JavaScript, I came across an amazing feature of JavaScript, which is called Hoisting

So, What is Hoisting ?

JavaScript allow us to use variables and functions, before they are declared

like this,

hoisting = "example";

console.log(hoisting);

var hoisting; 

// output will be :- example

here as we can see out put will be "example", though we used variable hoisting before it's declaration, we don't get any error.

  • Now let's see another example of hoisting
greet();

function greet() {
    console.log("Hello, This is an example of Hoisting");
};

// output will be:- Hello, This is an example of Hoisting

Now let's see formal definition of Hoisting,

Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top. This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.

hoisting.png

Now let's take another example of hoisting

console.log(hoisting);

hoisting = "example of hoisting";

var hoisting;

// output will be:- undefine

The Output will be undefined, Why ?

Note:- In Hoisting variables are only Initialized, not declared at the top. Variable initializations are not hoisted, only variable declarations are hoisted:

In Hoisting,

  • Functions:- functions are stored in the memory.

  • Variables:- variables are only initialized.

This diagram will help you to clear this concept,

image.png

Let's see Hoisting in global and local scope,

// hoisting in global scope
greet();

// hoisting in local scope
function greet() {
    name = "Avatar";
    var name;
    console.log(`Hello, I am ${name}`);
};

// output will be:- Hello, I am Avatar

Add a heading (1024 × 780px) (1200 × 780px).png

Note - To avoid hoisting, you can run JavaScript in strict mode by using “use strict” on top of the code:

// to restrict hoisting

"use strict";
hoisting = "example of hoisting";

// output will be:- error

Hope you like this blog, please do give feedback

Thanks !!

Did you find this article valuable?

Support J_Dheeraj by becoming a sponsor. Any amount is appreciated!