let and const instead of var

Until ES5, we could declare variables in any place in our code, even if we overwrote the variables declaration, as in the following code:

var framework = 'Angular'; 
var framework = 'React'; 
console.log(framework); 

The output of the preceding code is React, as the last variable declared, named framework, was assigned this value. In the previous code, we had two variables with the same name; this is very dangerous and might drive the code to an incorrect output.

Other languages, such as C, Java, and C#, do not allow this behavior. With ES2015, a new keyword was introduced, called let. let is the new var keyword, meaning we can simply substitute the keyword var for let. In the following code, we have an example:

let language = 'JavaScript!'; // {1} 
let language = 'Ruby!'; // {2} - throws error 
console.log(language); 

Line {2} will throw an error because a variable named language has already been declared in the same scope (line {1}). We will discuss the let and scope of the variables in the next topic.

The preceding code can be tested and executed at  https://goo.gl/he0udZ.

ES2015 also introduced the keyword const. Its behavior is the same as the keyword let; the only difference is that a variable defined as const has a read-only value, meaning a constant value.

Consider the following code:

const PI = 3.141593; 
PI = 3.0; //throws error 
console.log(PI); 

When we try to assign a new value to PI or even try to declare it again as var PI or let PI, the code will throw an error saying that PI is read-only.

Let's take a look at another example of const. We will declare an object as const:

const jsFramework = { 
  name: 'Angular' 
}; 

Let's try changing the name of the jsFramework variable:

jsFramework.name = 'React'; 

If we try to run this code, it will work. But const variables are read-only! So why is it possible to run the preceding code? For non-object types such as number, boolean, and even string, this means we cannot change the variable values. When working with objects, a read-only const allows the properties of the object to be reassigned or updated, but the reference to the variable itself (the memory reference address) cannot be changed, meaning it cannot be reassigned.

If we try to assign a new reference to the jsFramework variable as follows, the compiler will complain and throw an error ("jsFramework" is read-only):

// error, cannot reassign object reference 
jsFramework = { 
  name: 'Vue' 
}; 
The preceding code can be executed at  https://goo.gl/YUQj3r.