ES6 For Beginners : Using The Let keyword

In this post we will discuss what is the new let keyword in ES6. And how to use it. The let keyword is used to declare block level variables.

Before the let keyword we used var to declare variables but that has some issues. Take a look at the following code snippet

We have declare the name variable to be the string “john” then inside the if condition we are declaring another name variable with the string “jane”, finally when we alert we expect the value of name to be “john” but what we get is “jane”.

Even though we declared the second name variable inside the if condition it makes change to the global variable.


This problem is solved my using let as shown

As shown the variable inside the if condition is declared with the let keyword. This means that the global variable is untouched and we can use the variable inside theĀ  braces ({}) without having to worry about it making changers to the global scope.

In the snippets only if condition is shown but let can be used with any block of code that uses blocks so it can be used with for loops,functions ,etc


Using let With for Loop

So for example with a for loop we can use the let keyword as follows

Here instead of using var i=0 like we did up till now we use let i=0 this makes the variable i scoped to the for loop and does not pollute the global scope


Check out the entire list of ES6 tutorials and posts here.


Leave Me Your Questions And Feedback

Getting your feedback inspires me the most so hit me up in the comments here or on the comments section on my YouTube Channel or on twitter @uncutAcademy
Consider Subscribing / Donating
Subscribe To Mailing List
If my site was helpful to you, then please consider donating via paypal:
Prantik Vaghela

Prantik Vaghela (uncutAcademy)

Hi my name is Prantik Vaghela. I have done my Bachelors and Masters in Computer Science and am a web developer and now a Tutor through my blog. :-)