Contents

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.

1
const variable = 3;

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:

1
2
3
4
5
let variable = 3;
if (variable = 4) {
   add(variable);
}
do_something_with_this_variable(variable);

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.

1
2
3
4
5
const variable = 3;
if (variable = 4) {
   add(variable);
}
do_something_with_this_variable(variable);

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
1
2
3
 var globalVariable = 4;
 function funcScope() {
 }
  • the function scope
1
2
3
function funScope() {
    var functionVariable = 5;
}

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 { }.

1
2
3
4
5
6
function theNewScope() {
    let functionScopeVariable = 3;
    if (functionScopeVariable === 3) {
        let blockScopeVariable = 4;
    }
}

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.

1
2
3
let variable = 4;
// a very long and dense code comes here
let variable = 10;

This code above will return you an error.