Var declarations were the only type of variables before ES6, and Let and Const were introduced to fix some of its issues. The main differences with Var are its scope, its ability to be re-declared and updated, and the fact that it is hoisted. Now, as far as scope goes, var is globally scoped if it is declared outside of a function, functionally scoped if declared within one. For example:
If pizza were declared outside of the function, we would have seen ?delicious? and all would be right with the world. So far, this doesn?t seem like a big deal. But when combined with the fact that var can be redeclared, it?s? easy to see where things can get messy. If we can redeclare a var that?s globally scoped at any time, one small mistake could ruin otherwise perfectly good code. This is a big reason why let and const are preferred. Another little unique wrinkle about var is the fact that it?s hoisted. I?m not going to go super deep into hoisting, but for our purposes, it?s a pretty simple concept. Take this for example:
We get undefined instead of an error, because variables declared with var are ?hoisted? to the top of their execution context. This is not the case with let or const.
Let variables, unlike var, is block scoped, which means it scoped to a bunch of code surrounded by curly brackets. This can mean a function, or a loop or what have you. Another difference between let and var is that let can be updated, but not redeclared.
This will not give us an error, but this will:
This is the main difference between let and const. They?re both scoped the same, but const cannot be updated or redeclared whatsoever.
So just to recap, the main differences are: var declarations are globally or functionally scoped while let and const are block scoped. Var can be updated and redeclared, let can be updated but not redeclared, and const can do neither. Var is hoisted, while let and const are not.
That?s all folks! Thanks for reading.