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
const are hoisted, but:
varis initialized with
Here’s the explanation.
var keyword, the
a variable below is hoisted and initialized with 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:
const keyword, just like
let, throws an error, but this error is different: