What is Hoisting in JavaScript?

Hoisting is JavaScript’s default behavior to push declarations of variables to the top of its scope. When JavaScript compiles the code, all the variables declarations are moved to the top of their global or functional scope. Hoisting does not happen inside your code but it happens when JavaScript compiles your code. Even the functions are hoisted in JavaScript.

console.log(say_hello()); //Output- Hello World
function say_hello(){
  return "Hello World";
}

In the above example, you can see that even though function say_hello has been declared after being called inside the code. It will still output “Hello World” rather than throwing the error.

name = "Joe";
console.log(name); //Output- Joe
var name; //Name variable declaration

Here, you can see even though variable “name” is declared after it has been provided with value. It will still output “Joe”.

Another important thing to note is that JavaScript only hoists the declarations but not the initialization. In the example below, you can see that the age is undefined because it was declared after.

var name = "Joe";
console.log(name + " age is " + age); //Output - "Joe age is undefined"
var age = 21;

class, let and const are also hoisted to the top of the block scope. However, they are not initialized. The variable is in a “temporal dead zone” from the start of the scope until it is declared. In the example below, if foo function is invoked before declaration, it will throw a reference error. You can learn more about let and const at JavaScript let and const.

foo(); //Output- Uncaught ReferenceError: Cannot access 'foo' before initialization 
const foo = function(){
  return "foo"
}
car = "Toyota";
console.log(car); //ReferenceError
let car; 

I hope this post was helpful to you. If you like my post, follow me @twitter/andramazo.

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top