The confusing let, var, and const of javascript

Know the concept and save yourself

As we know there is two way to declare a variable either declare with var or declare let. Now the matter is when to use var and when to use let. For this, we need to know the main difference between both.

The main difference between let and var is that scope of a variable defined with let is limited to the block in which it is declared while a variable declared with var has the global scope. So we can say that var is rather a keyword that defines a variable globally regardless of block scope.

Javascript var

Here is an example program, see I got the output from the outside scope. We can access var from anywhere inside the function that’s why it is also known as function scope.

Javascript let

Here is a program of let, see the output. We can’t access the variable from outside the scope. In javascript, let is known as block scope, because we can access the variable from only inside the block(for example for, while, if, loop blocks, or any other individual block).

Why both?

In early 2015 before ES6 javascript introduced only “var”. Javascript introduced “let” because sometimes we need something accessible only from the inside scope like other programming languages.

Javascript const

In javascript, const is the same as let but the main difference here is we can’t define it twice. If we need to overwrite the value of the “let” variable is possible but it is not possible to overwrite the value of a const variable, reassign is restricted here. Const allows updating the value when this is an object. Here is an example

Conclusion

Obviously, you need all of these in your day-to-day life if you are a javascript programmer. But having these concepts can save you from horrible mistakes.

Have a great day!

Leave a Reply

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