arrow-rightgithublinkedinscroll-to-topzig-zag

The difference between let and var in ES6

Last Updated On

In new projects, I’m very fortunate to have the ability to use new JavaScript specification. I’m talking about ES6 (aka ES 2015). I really like its features like export, import, fat arrow functions, modules, classes, etc. I know ES6 comes with way more features, but right now I really want to put some light on a very basic thing like keywords let and const.

The problem

On a daily basis, many developers use var when they have an ability to use let (at least from what I’ve seen). I’m not trying to point that this is the most horrible thing in the world. Not even close. What I’m trying to say is if you have an ability to do something in a little bit better way, why would you omit this option? But instead of making a bold statement lets take a look at theory & example and figure out why would I say that.

Theory & example

Let’s start with an example:

if (true) {
    var color = 'black';
}
console.log(color);

If you would run this code, you’ll get  black in the console. However, I defined my color inside the block. Why is it accessible outside? Because this how JavaScript worked before ES6.

This is another example from the same story:

for (var i = 0; i < 5; i++) {

}
console.log(i)

Taking into account that I defined i inside the loop I still can access it outside. You’ve got the idea, right? What If I need to use the same variable inside and outside the loop? So, they can be overwritten. This might be not the best example in the world, but when you work with a large codebase these types of mistakes are usually the most difficult to find.

But, what would happened if I would take two examples above and replace var with let?

if (true) {
    let color = 'black';
}
console.log(color);
for (let i = 0; i < 5; i++) {

}
console.log(i)

Ha, I’ve got an error: variable isn’t defined. It means that right now we have an extra layer of protection by introducing a block scope! From now each variable that is defined inside the loop, conditional statement or in other words in a block will be accessible only inside this block. Is this better? I think yes.

Conclusion

So, do I need to go and refactor all of my vars with lets? No. I would do it only if you have needs and time for that + you’re sure that it won’t break your functionality. The main point of this article is to introduce a new keyword and make you feel more comfortable with it.