var, let and const
1. var
It is an old way to declare variables in JavaScript and it’s now the weakest keyword to define a variable. The variable declared by var may or may not be reassigned and because it is in function scope, the variable may or may not be used for the entire function. If the variable is reassigned accidentally within a for loop (block scope), then that’s when things can easily go wrong. People can overwrite parent assignments in this case. For example,
var foo='outside';
if(true){
var foo = 'inside'
console.log(foo); //print inside
}
console.log(foo); //print inside
To clarify, var is in the function scope. So if you do reassignment in a function, the variable outside the function wouldn’t be changed.
var foo='outside';
var fooFunction = function(){var foo='inside'}
fooFunction();
console.log(foo); //print outside
Another potential issue with var is that it can be referenced before it’s assigned. For example,
var x = 'foo';
console.log(x); //foo
console.log(y); //undefined, no errors!!
var y = 'late foo'; //late foo
console.log(y);
There are no errors when using the variable before the declaration. Javascript engine reads the above script as
var x ='foo';
var y ='late foo';
console.log(x); //foo
console.log(y); //undefined, no errors!!
console.log(y); //late foo
Although people can avoid this issue by using ‘use strict’, const and let are still stronger and can reduce potential error and make the code more clear.
2. let
When it comes to the situation I need to reassign a variable, let is more welcome than var after ES6. The reason is that let is in block scope which means it only exists within its own scope. For Example,
let foo='outside';
if(true){
let foo = 'inside'
console.log(foo); //print inside}
console.log(foo); //print outside
After the if condition, foo is equal to ‘outside’ rather than the value we have inside the if statement (‘inside’).
3. const
const is used when you don’t want to reassign the variable. It stays constant once it’s declared. As a result, const is always a default option for me if I don’t need to reassign the variable. In this way, we can also avoid the case when we occasionally declare the same variable name in other files.