Hoisting in JavaScript

hoisting in javascript

Hoisting is a default behavior in JavaScript and not a feature. Here it allows us to use the variables and functions before declaring it. All the declarations of variables and functions are moved to the top of the scope. In other programming or scripting languages we cannot use a variable or function before declaring it.

In Javascript, compiler moves all variable and function declarations to the top so there wonโ€˜t be any error.

Lifecycle of a variable:

Declaration โ€“ Registers a variable in the corresponding scope.

Initialization โ€“ Allocates memory for a variable.

Assignment โ€“ Assign a specific value to the variable.

In Javascript only keyword var is hoisted and let and const are not hoisted.

Variable hoisting:

As said before only keyword var is hoisted.

//variable hoisting
a = 10;
console.log(a);
var a;
Output:

10

This above code will be rearranged in memory as declaration moves to top. So it works like,

var a;
a = 10;
console.log(a);

Now, what will happen if we try to access a variable before initialization?

console.log(a);

var a = 10;
Output:

undefined

It is because only declaration is hoisted that is move to the top but initialization is not hoisted. So, the variable is assigned undefined value if we try to access before initialization

The above code will be in executed in memory as follows and return undefined

var a;
console.log(a);
a = 10;

Now, what will happen if we try to use a variable that is not declared?

This can happen in cases where the number of lines of code is large and we cannot find the variables declared.

cosole.log(a);
a = 10;

Here reference error is thrown.

Keypoints:
  • undefined value is assigned when we try to access a variable before initialization.
  • Reference error occurs when we use a variable that is not declared

Function hoisting:

Here function declaration moves to the top of the scope.

var a = 10;
add(); // called before declaration
function add(){
  b = 20;
  console.log(a+b);
  var b;
}
console.log(b); // variable b is hoisted inside the function

Here the function declaration is moved to top. Variable a is declared outside so global scope but variable b is declared inside the function so it will be hoisted inside the function. Variable b is moved to the top of the function not outside the function scope. It has local scope. If we try to access a variable b outside the function it will throw reference error.

Another thing to remember is only function declaration is hoisted and function expressions are not hoisted.

var a = 10;
add();
var add =function(){ // function used in an expression
  b = 20;
  console.log(a+b);
  var b;
}

This will throw type error.