Javascript - what is hoisting and why does it matter?

I recently created a post on the differences between var, let and const. One thing that I realised writing that, was that I used the term "hoisting" a lot. Hoisting is the interpreter moving variable and function declarations to the top of the scope. Where scope differs whether you declared the variable as let or var, as let is block scope and var is function scope.

Hoisting is the interpreter moving variable and function declarations to the top of the scope

A small code example

The below is an obvious mistake. The console.log is before the test variable is declared. But due to hoisting this does not fail:

(function(){
   //var test; gets inserted here, but not assigned!
   console.log(test);
   var test = '123';
}());

Because declarations are hoisted the variable test is actually declared at the top of this function. But not assigned. Basically the above will become this:

(function(){
   var test; //variables are undefined if not assigned
   console.log(test);
   test = '123';
}());

This is the basis of hoisting. Moving variables to the top of the scope.

I hope this clarified hoisting, let me know if it didn't!