JasperValero.com

JavaScript

The Magic Of The ES6 Let Keyword

Posted on .

The Magic Of The ES6 Let Keyword

Introduction

In this post, you’ll learn about the refined scope control provided by the ES6 let keyword. With let, you can keep your variable scope contained within the enclosing block.This can be a great alternative to the enclosing function scope that the var keyword invokes. Using it will allow you to write more resilient code that is less susceptible to overwriting your variables.

Working With var

First take a quick look at one of the caveats of var:

In the code example above I’ve accidentally overwritten my default gamer tag value inside of the loop. It made sense that I would want to use the semantic variable name of ‘gamertag’ both inside and outside of the loop. The problem is that var won’t allow me to. I would have to get creative with my variable names to avoid the undesired outcome.

More Control With let

Now look how easy it is to do what we want using the ES6 let keyword:

The code is nearly identical. The only changes I made is to use ES6 let keyword for the ‘i’ iterator as there is no need to create it with a scope outside of the loop. I also used let for ‘gamertag’ to keep its scope within the {} scope of the for loop. Once we exit the loop, we’re right back to referencing the version of the ‘gamertag’ variable we created at the top.

As you can see from the code above you can use both var and let at the same time. Both are valid keywords in ES6. It is worth mentioning that some believe that the ES6 let keyword is the better way to create variables in ES6. I plan on making use of both for now.

Conclusion

Now that you’ve learned about the ES6 let keyword you have more control of your variable scope. It will allow you to use your variables in a much more efficient manner. How awesome is that?

I’d recommend taking some time to identify the right time to use let versus var. It will probably take a little practice to get used to the idea that scope can differ based on how you create your variables. There no time like the present to get started!

profile

Jasper Valero

http://jaspervalero.com

Rockstar engineer working hard to dent the universe.

Navigation