1. Home
  2. >
  3. What is Hoisting?
2

What is Hoisting?
Manish Kumar Manish Kumar

During compile phase, just microseconds before your code is executed, it is scanned for function and variable declarations. All these functions and variable declarations are added to the memory inside a JavaScript data structure called Lexical Environment. So that they can be used even before they are actually declared in the source code.

Reason for WEIRDNESS

* The answer lies in the Global Execution Context. In the memory phase, the variables will be initialized as *undefined* and functions will get the whole function code in their memory.This is the reason why we are getting below outputs.

# interview# javascript# hoisting
//JavaScript only hoists declaration not initialization
// code example 1

var x = 7;
function getName(){
    console.log("Hii JavaScript");
}

getName();
console.log(x);

/*
Output:

>  Hii JavaScript
>  7
*/

// code example 2

// in most languages, both lines which are below their declaration will give error. Not in JS though. 
getName(); 
console.log(x); 

var x = 7;
function getName(){
    console.log("Hii JavaScript");
}

/*
Output:
>  Hii JavaScript
>  undefined
*/


// code example 3

getName();
console.log(x);

function getName(){
    console.log("Hii JavaScript");
}


/*
Output:

>  Hii JavaScript

>  Error: x is not defined   // note that not defined here and "undefined" in sample 2 are totally different.

- Not defined: We have not initialised the value for variable anywhere in the entire code and in memory space. 
- Undefined: 

__Hoisting__ is a concept which enables us to extract values of variables and functions even before initialising/assigning value without getting *error*

*/

// code example 4

function getName(){
    console.log("Hii JavaScript");
}

console.log(getName)

/*
Output:

> f getName(){
      console.log("Hii JavaScript");
  }
*/

// code example 5

getName();
console.log(x);
console.log(getName)

var x = 6;
function getName(){
    console.log("Hii JavaScript");
}


/*

Output:
>  Hii JavaScript

>  undefined

>  f getName(){
      console.log("Hii JavaScript");
  }
*/

// code example 6 : using arrow function

console.log(getName)

var getName = function () {
    console.log("Hii JavaScript");
}

var getName = () => {  // use fat arrow function  
    console.log("Hii JavaScript");
}

/*

Output:

>  undefined //it is because they behave as variable and not function. 

*/

/*
But why undefined?

When JavaScript engine finds a var variable declaration during the compile phase, it will add that variable to the lexical environment and initialize it with undefined and later during the execution when it reaches the line where the actual assignment is done in the code, it will assign that value to the variable.
*/

Discussions

# interview# javascript# hoisting