Hoisting in JavaScript

·

2 min read

Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.

In this blog, I will tell about hoisting of variables and functions in JavaScript.

variable means anything that can change from one condition to other, a variable stores the data value that can be changed later on.

In JavaScript we use three variables:

  • var
  • let
  • const

Now, let's see how hoisting works on these three functions.

VARIABLE HOISTING

ex-1

       console.log(lamborghini) // Output:undefined
       var lamborghini = "car"

In the above case output will be undefined because JavaScript reads code like shown in the below code

ex-2

       var car
       console.log(lamborghini) // Output:undefined
       car = lamborghini;

But still the above code will show undefined as the code hoists the declaration but not the assignment.

Let us see an example with 'let' declaration

ex-3

       console.log(car)  // ReferenceError: car is not defined
       let car = "lamborghini"

Here we get a reference error, instead of undefined.

Let's see an another example

ex-4

       let car;
       console.log(car)
       car=lamborghini;   //output: undefined.

In the above example, let is assigned but not initialized. So the output shows undefined

In JavaScript the var declarations are processed first in the background. Then, initializes are processed let and const are hoisted but can't access until initialize. Therefore, it shows that var declarations takes first before code execution.

FUNCTION HOISTING

ex-4

       car();

       function car(){
       console.log('lamborghini');
       }

The above example code runs without any error. This shows that all function will be hoisted in JavaScript, so that function can be called before declaration.

Summary:

JavaScript only hoists declarations, not initializations. Thus, it is good practice to define variables in the beginning of code. It also helps in avoiding bugs.