Hoisting differences related to keywords var, let and const in JS

In this article. we'll go over the differences between `var`, `let`, and `const` as related to hoisting

By: Ajdin Imsirovic 27 January 2021

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.



Feel free to check out my work here: