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.
All the variables built with var
, let
, and const
are hoisted, but:
var
is initialized withundefined
let
andconst
are uninitilized
Here’s the explanation.
With the var
keyword, the a
variable below is hoisted and initialized with the undefined
value.
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:
The const
keyword, just like let
, throws an error, but this error is different:
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.