We all know that the var keyword should not be used in our code, and that we should mostly use let and const. Weโ€™ve probably already read articles about the reasons for this and how to use them properly. But what are the differences between var, let, and const, in relation to hoisting? Letโ€™s find out.

Hoisting differences in var let and const in JS

All the variables built with var, let, and const are hoisted, but:

  • var is initialized with undefined
  • let and const are uninitilized

Hereโ€™s the explanation.

With the var keyword, the a variable below is hoisted and initialized with the undefined value.

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

The undefined value will be logged as per the first line of code above.

However, with the let keyword, the b variable below is hoisted, but not initialized with the undefined value, or any other value. Thatโ€™s why this code will throw an error:

console.log(b);
let b = "b";
// Uncaught ReferenceError: b is not defined

The const keyword, just like let, throws an error, but this error is different:

console.log(c);
const c = "c";
// Uncaught ReferenceError: Cannot access 'c' before initialization



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.