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,

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.

Another potential issue with var is that it can be referenced before it’s assigned. For example,

There are no errors when using the variable before the declaration. Javascript engine reads the above script as

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,

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.

Developer with 3 yrs of industrial experience in developing scalable web applications.