Hoisting in JavaScript

javascript hoisting

Hoisting is JavaScript concept which make JavaScript different from language Java.

In Java every variable created in code have block level scope. Means if we have create any variable that will have its visibility limited into that block in which it was declared.

So if we use variable above from the declaration it will gives error.

But in the JavaScript, the variables can be used before declared, this kinds of mechanism is called Hoisted. It’s a default behavior of JavaScript.

You can easily understanding in the below example in detail.

getEmp();
function getEmp() {  
  var emp1 = 20; //The assignment values is 20.  
  console.log(emp1); //The output is 20.
}

In Example we have call function getEmp before it declared. So as we know JavaScript use interpreter or we can say single thread application it should through exception because we called function which is not declared yet.

But as JavaScript support hoisting it will interprets function like below code:

function getEmp() {  
  var emp1 = 20; //The assignment values is 20.  
  alert(emp1); //The output is 20.
}
getEmp();