ES6 Variables
Variables
Before ES6, there was only one way to define variables: using the var keyword. If you do not define them, they will be allocated to the global object. Unless you were in strict mode, any undefined variables would result in an error.
Now, with ES6, you may define variables in three ways: var, let, and const.
Example
var
var x = 5.6;
If you use var outside of a function, it is in the global scope.
When you use var inside a function, it belongs to that function.
If you use var inside of a block, such as a for loop, the variable remains available outside of that block.
var have a function scope rather than a block scope.
Example
let
let x = 5.6;
Let is the block-scoped version of var, which is only applicable to the block (or expression) in which it is defined.
If you use let inside a block, such as a for loop, the variable is only available within that loop.
The let function has a block scope.
Example
const
const x = 5.6;
Const is a variable that, once created, cannot be changed.
Const has block scope.
The keyword const is quite deceptive.
It doesn’t specify a constant value. It establishes a constant reference to a value.
Therefore, you cannot:
- reassign a constant value
- Reassign a constant array.
- Reassign a constant object.
But you can:
- Change the elements of the constant array.
- Change the properties of the constant object.