ES6 – Variable Declaration with Let and Const

In ES6 there are 2 new ways by which we can declare a variable. Let’s discuss about them in detail.

For ES6 we will use a index.html, with some colors which will help us understand ES6 in a more better way in upcoming blogs.

Let’s write some code in ES5, and after that let’s convert the code to ES6 to understand the difference between ES5 and ES6.

Code in ES5

In ES6 const is for constant i.e for value we do not want to change the value. And let in ES6 is similar to var in ES5.

Code in ES6

This is not the only new update with let and const. That is because variables declared using var in ES5 are function scoped and variables declared with let and const are blocked scoped.

Function Scope vs Block Scope

Let’s write some simple code of lines in ES5 and ES6 to understand this.

In ES5

In ES6

Both the code worked fine. Now let’s move the console statement out of the if block.

Code in ES5 worked as var is function scoped and as soon as we moved the console statement out of if block in ES6 we got an error as variables declared in ES6 are block scoped.

If we want still want to use the variable outside the block then we need to declare the variables outside the block in that case. Also, to keep in mind, while declaring the const we need to provide value to it, else it will throw us error.

There is one more difference between how we declare variable in ES5 and ES6. What happens when we use a variable even before declaring it in the code. I hope you remember this from my previous blog.

We get undefined

Let’s see how it works in case of ES6.

Let’s have a look at another simple but interesting example.

We get output as 5 in the end as the value of i has been overridden in ES5 and the latest value of i is being displayed. Let’s see how it works in ES6

The value of i is not overridden as variable is blocked scoped in ES6. Variable i is treated as a different variable in case of ES6.

About the author

Deepak Sood

Deepak Sood is Lead Consultant in an IT firm holding expertise in Devops and QA Architecture with 8 years of experience.

His expertise is in building highly scalable frameworks. His skills include Java, Configuration Management, Containers, and Kubernetes.

Reach out to him using contact form.

View all posts

1 Comment

  • Awesome Article I had not idea about let, var and const and it has lots of confusion when some ask me about that.

    Now its clear things that i wanted

    Thanks a lot for sharing this article…!!