Javascript Hoisting

Javascript Hoisting

You may have encountered this in javascript when you console.log() a var before declaring, instate of getting an error we get a strange value called undefined let's see what's happened behind the seen.

What is hoisting

Hoisting is the process in javascript by which we can access the variables and functions even before we have initialized it without getting any error

let's take some example

1    var one = 2
2    function getValue(){
3        console.log("hello world")
4    }
5    console.log(one)  //  2
6    getValue()  // "hello world"

as you can see in the above javascript example nothing is new to us, we defined and initialize variable one on line 1, and on line 2 we defined a function and call both of them after defining and ve got their respected value

but what happens when we tried to console.log() the variable and invoke the function before defining them let's see

1    console.log(one); 
2    getValue();
3   
4   function getValue(){
5        console.log("hello world")
6    }  
7    var one = 2;

imgone.png

here you can see in the above example var one and function getValue() got hoisted but why the value of var one is undefined and the function return hello world before I explain this, let's see one more example

1    console.log(one); 
2    console.log(getValue);
3   
4   function getValue(){
5        console.log("hello world")
6    }  
7    var one = 2;

imgone.png

so this is the same value for variable one and function getValue stored in a memory creation phase in the memory component of the global execution context, As we tried to access the value before defining javascript simply give the value stored in a memory, But in the case of a function, the whole function is stored in a memory during the memory creation phase as you can see in the above image,

imgone.png

imgone.png

Function declarations and arrow functions are hoisted?

In the case of function declaration and arrow function, we can not invoke the function before the declaration because both types of declaring the function act like a variable and during the memory creation phase, the value of this function is undefined and if we tried to invoke this type of function we will get a type error,

Difference between undefined and not defined

From the above examples, we definitely can say how we got undefined for the var one but in case I tried to access some variable that is not declared or defined in an entire code so javascript throws a reference error: one is not defined Let's see

1    console.log(one); 
2    console.log(getValue);
3   
4   function getValue(){
5        console.log("hello world")
6    }  
7    //var one = 2;

imgone.png

In the next article, we will try to understand how the javascript function works and take a look at the variable Environment,