Understanding “let” and “const”

let and const are different ways of creating variables. We already know var. var creates a variable in JavaScript.

Now the thing is, some variables never change. They are so-called constants. Technically they are. They are all just variables because JavaScript knows variable.

With ES6, a version of JavaScript two different keywords were introduced – let and const.

var still works but it is highly recommended to use let and const. let and const are changing something behind the scene about the scope of variables.

But the most important takeaway is –

Use let if you want to create a variable that really is variable. Use const if you plan on creating a constant value, something you assign only once and never change.

It's all simply the same as var, just in a more modern way and in the case of const it's clearly showing that this is never going to receive a new value.

More Into var, let and const

Let's dig more into var, let and const for a better understanding.

First thing we need to know about var variables is we can reassign them. We can also update them. Another thing we need to know about var variables is how they are scoped.

Scoping essentially means where are these variable available to us.

var variables are function scope which means they are only available inside the function where they are created. If they are not created inside any function they are globally available.

let and const are block scoped. What does this means? If you create let or const variables inside any code blocks i.e two curly braces, they will only be available to those code blocks.

For a better understanding, here's a video from Zac Gordon on var, let and const.

If you create a var variable inside a conditional block, you will see that the variable is actually available in the global scope but it shouldn't have been.

That's why in these cases let and const are highly encourages instead of var.

Further Readings

Leave a Reply

Your email address will not be published. Required fields are marked *