var has a function scope. This means it is accessible anywhere in the function it is defined inside. See this example:
As you see decision variable defined with
var was availabe inside the function scope, but when we tried to log it outside the function the console throws an error
decision is not defined as if it’s never existed.
On the contrary,
const have block
Surprise! Logging the value of decision inside the expression block resulted in the predicted string while doing the same out of the block throw error and out of the function scope also throws an error.
The same happens with
Variables declared with var are hoisted to the top of their scope. It is important to notice that the variable declaration is what is being hosted not the assignment.
What happened?! The
console.log() function will not get executed until hoisting any
var variable. Therefore,
var x; will go up to the top of the global scope. Then
console.log(x) is executed and logs undefined, because x has no value at that time. The x is assigned the value 5. It will look like this:
Because of that if we
console.log(x) after that it would log 5 to the console.
This quirky behavior can introduce bugs in larger programs.
const are not hoisted.
var variables can be re-declared and reassigned different value multiple times in the same scope.
let variables can not be re-declared but can be reassigned in the same scope.
const variables can not be re-declared or reassigned in the same scope. In addition to that they must be declared and assigned a value at the same time. So we can not do that:
But we must do that:
1const y = 5;
So if your variable would have changed values, declare it using let, if not always use const.
These differences between them and var will prevent naming conflictions.
For the mentioned reasons you should use
const in all cases except when the variable would be reassigned new values. At such cases use
let instead. Most of articles recommend developers to avoid using
var. Why would anyone use var anymore?!
For further readings: