With ES6, two new keywords, let and const, were introduced for declaring variables. Until then the only available keyword was var. Const as the name implies can not be changed for primitive values, however, we can change the properties of constant objects.
The focus of this post is on var and let which differ in three ways:
A variable defined outside of a function or block is a global variable as it can be accessed anywhere in the current document. A variable defined within a function has a local or function scope as it can not be accessed from outside that function. With ES6 the variables can be scoped to the nearest pari of curly braces and, therefore, can not be accessed from outside.
As can be seen from the code above, let variables are both function and block scoped and can not be accessed from outside their respective scopes. Var on the other hand is only function scoped and can be accessed from outside the block.
Variables defined with let or var can be reassigned which makes perfect sense. However, when we try to declare a variable that has already been declared, both exhibit different behaviour.
With let, a variable can only be declared once, so if you or someone from your team tries to redeclare it, you will get a reference error. With var, the variable gets overwritten and this increases the risk of overwriting useful data and can break your code.