Meet the ES2015 (ES6) Variables — var, let, const
Before, all variables in Javascript use only one keyword to declare a variable and that is var. With the release of ES2015 (ES6), variables can be declared in two new ways, let and const. Now, it’s easier to distinguish the variable’s scope and purpose.
Variable
— is what you use to store information/data that can be referenced as needed
var variableName = “value”
let
— gives your variable the ability to limit its scope within a block (block scope), statement, or expression
BEFORE:
If you have used a variable with the same name in different scope, you will override the variable’s value.
NOTE: The value that was read by the console was the variable inside the for loop.
//Result in console2
NOW:
By using let, we can be sure the variable is just within the scope of a block, statement or expression.
Block:
Anything inside { }, be it a function, within an if statement or just the inside a block { } itself.
NOTE: The variable that was read by the console is the one outside the for loop.
//Result in console30
const
— creates a read-only variable making it a constant (something that can’t be changed once a value is assigned). Also, same as let, this is block scoped.
BEFORE:
Before we use the UPPERCASE letter when we name a variable to determine that it is a constant, now you can use the const keyword to identify it. An issue that arises before is that you can accidentally assign a new value to your constant.
//Result in the console:newAPIKEY
NOW:
An error will occur if you accidentally assigned a value to it.
//Result in the console:"error"
let & const are the new family members of the variable in the ES2015 version.
Definitely a big help in preventing unwanted bugs. If this lesson has helped you in anyway, you can give it a ❤ or share it out. Thanks! :)