Basically, as we all know var, let and const are the three different ways to create or declare variables in javascript. So, let’s try to understand how they are different from each other.
From the year 1995, when javascript was created, there was only one way to declare a variable that is var. The other two came nearly at 2015 in ES6. Since then let and const are very popular among most of the javascript developers.
Const :
‘Const’ is often the best option for declaring variables. ‘Const’ is an abbreviation for constant meaning the variable shouldn’t change. The ‘const’ declaration stops the variable being overwritten by any stray variables. Meaning you can’t assign pi to another value. We can test this out by using the console window in chrome. Open up the Const Sample by clicking the link above. With the console window type in our constant pi. This will give us our value 3.14159. If we try to change the value of pi we get an error.
You should only use a ‘const’ for declaring variables that shouldn’t change. If you expect the value to change each time a script runs eg a score or age, you should use the keyword ‘Let’.
Let :
‘Let’ is often the best option for declaring variable were the value is likely to change similar to how var works. The difference being ‘Let’ variables are block-scoped so helps defend against those var scoped errors. We have a basic ‘Let’ example below. In the script, we’re using the score to keep track of the user’s progress in a game. In a typical game as a user plays the score will change. Unlike ‘const’, if you try to reassign the value we can successfully change the score. In the sample below I’ve just added 1 to the score each time showing how the ‘Let’ keyword assigns the new value. You can try it out with the download link above.
This is a rather simple example lets look at a more complex sample where and when you should use ‘Let’ instead of a ‘Const’.
Var :
As mentioned, a variable being declared using willvar
be function scoped, meaning it will exist within the scope of the function it’s declared inside of. As you can see, the variable declared with var
inside the function, is not reachable from outside the function. With that said, other types of blocks — like if-statements, loops etc — will not be considered as a scope.
Using var
, the variable name
is available outside the if-statement it was declared inside of. This is because they’re in the same scope. However, with the introduction of ES6, two new ways of declaring variables were introduced.