Const and Let
The problem with just using var
is that this is valid:
JAVASCRIPT
1var firstTime = "something original";
2var firstTime = "overwriting the original";
This example is easy to understand, but imagine a huge codebase with several thousand line files. If firstTime
is declared on line 1, and then redeclared on line 1800, it can be easy to miss.
let
and const
are block-scoped. A block is simply a chunk of code wrapped by curly braces {
and }
. This means that any variables declared using either let
or const
are only available for use within the {
and }
symbols.
JAVASCRIPT
1if (true) {
2 let onlyHere = "this is only available here";
3}
4console.log(onlyHere); // Uncaught ReferenceError: onlyHere is not defined