Difference between var, let, and const based on declaration and initialization

In the previous post, you learned how to create a variable. In this post, you will see the difference between var, let, and const.

Var :

It is not recommended to use var to create a variable, the following is the reason for that:

Figure 1

Output of the above code:

Figure 2

With var, the variable with the same name can be redeclared and the memory will have two variables of the same name. When we access the variable ‘a’ the value we get is 11 as the browser will use the latest value of ‘a’. This creates a problem when we have a big program with lots of lines and we forget if we have already used a variable name, and we redeclare it and its value gets updated and we end up having errors.

let:

It is recommended to use the let keyword to declare a variable. With the let keyword, we cannot redeclare the variable but we can reinitialize the value.

Figure 3

Output of the above code:

Figure 4

As you can see in Figure 4, the code in Figure 3 generates an error because once we have declared a variable using let, we cannot redeclare it. We can definitely reinitialize it, giving it a new value. For example:

Figure 5

The output will be:

Figure 6

The value of the variable ‘a’ has been updated and the browser uses the latest value of the variable ‘a’.

const :

With the const keyword, we can neither redeclare the variable nor we can reinitialize the value. Once a value is initialized to a variable it is constant. If we try to redeclare a const variable, we will get the Syntax error shown in Figure 4. And if we try to reinitialize the value to a const variable then we get the TypeError shown below:

Figure 7
Figure 8

One should always use the let keyword to declare variables. If you know that a particular value will not change in the entire program then you must declare it using the const keyword.