What do the let and const keywords do?

Question

What do the let and const keywords do?

Answer

Before ES6, all variables were essentially declared using var. One issue with var was that when you defined a variable inside of a function, regardless of the block scope in which it was defined, it would become local to the entire function block. In addition, there was no simple way to make a variable unchangeable, so that once you declared a variable it could not be changed.

ES6 introduced the let and const keywords for declaring variables, which helped to address these problems.

The let keyword is used to declare variables that could be changed, like a variable used as a counter in a loop, similar to how var is used. However, it fixed the issue above, so that variables are block-scoped only inside the blocks they are defined in, even inside of functions.

The const keyword is used to declare variables that should not change, and would throw an error if you did try to change them. For example, you might use a variable PI that stores the value of pi, which should not be changed, which addressed the second issue above.