ES6 introduced two new ways of declaring variables let and const. Before the introduction of let and const, variables could be declared only using var. In the next video, let us look at what context these keywords are used in and how declaring a variable using these keywords differs from declaring variables using var.
In the last video, you learned that variables declared using let keyword can be modified. As the name itself suggests - it lets you change the value. The keyword const, on the other hand, is a bit stubborn and you can't change the value stored in it. Thus, the variable remains constant and if you try changing the value stored in a const variable, it then throws an error saying “Uncaught TypeError: Assignment to constant variable”.
Thus, you must declare a variable using the let keyword when you want to change its value in future. On the other hand, you must declare a variable with const keyword when you do not want to change its value ever!
Now you might be wondering that var keyword, that you have been learning till now in ES5, is similar to the let keyword. You can change the value in variables declared using either keyword. Well, there is difference between let and var. Let’s see what that difference is in the next video.
In the last video, you learned a very important difference between var and let / const keywords. Variables declared using var keyword are function-scoped whereas variables declared using let and const keywords are block-scoped.
Now let’s see another difference between let / const and var keywords.
In the last video, you looked at how the variables declared using the var keyword are hoisted to the top of their scope and the variables declared using let / const keywords are not hoisted.
So to summarise, in this segment you learned about let and const keywords. You learned how a variable declared using const keyword cannot be changed and how a variable declared using let keyword lets you change itself. (This is actually a nifty trick to remember what they do!)
You also learned that let/const are block scoped, and hence can be quite useful in situations where you’re required to use a variable multiple times in a program, such as in the case of loops or conditionals.
You also learned that unlike var, the variables declared using let/const keywords are not hoisted to the top of the scope. Thus, you must always prefer to declare all your keywords using let and const keywords as compared to declaring them using var keyword, when following the ES6 syntax.
Additional Reference:
'let' me be a 'const'; not a 'var'