ES2015 - const and let
const
It’s an alternative to the var keyword for declaring variables. When using the const keyword we create a variable which value can’t be redefined.
|
|
In that case we are declaring a value which holds the value of 3.
If by any case we try to change that value we will get an error coming that says we can’t change a const value.
So you might be thinking: why shall I declare a variable which a value I can’t change? What is the use of it?
Using const you get a kind of a protection layer. When you are writing long codes you might end up overwriting a variable you didn’t want to and const will protect you from that. Also const will protect you from typing mistakes like this one:
|
|
In this example I made a mistake when coding. My intension was to use the ‘===’ instead of ‘=’. Just a simple and pretty common typo mistake that will change the expected behavior of my code.
If I take the precaution of using const as my default way of declaring a new value I’ll be safe for, at least, this kind of mistake.
|
|
In this case JS will return me an error saying that I’m trying to change the value of an const value which is illegal.
const and objects
const does not make objects immutable. It works only with primitive values. So if I have an array declared with const I can still add and remove data to this array.
other useful use of const
const is useful for creating variable that we don’t want to redeclare. If for any obscure reason you end up redeclaring a variable created with the const keyword you will get an error back.
let
The let keyword bring the block scope into Javascript. Before let comes into JS we had only two types of scopes:
- the global scope
|
|
- the function scope
|
|
Let made possible to restrict the use of a variable to a new type of scope: the block scope. A block scope is the code in between { }.
|
|
In this case the variable blockScopeVariable is valid only inside of the if block and it is not accessible outside of it.
let will also introduce the idea of being unique inside of a block. Just like const as soon as you declare a variable you can’t declare it with again.
|
|
This code above will return you an error.