Difference Between Let and Var in Javascript

Difference Between Let and Var in Javascript
Rating: 5 - 1 Votes

Difference Between Let and Var in Javascript

Today, we will discuss what is the actual difference between let and var. I will try my best to explain it to you in very clear and concise manner since there are a lot of lengthy articles about it. There are actually 2 major differences.

1.  Var keyword is generally used with Javascript ES5 syntax and we do have major issues when its come to scoping. Let keyword is part of Javascript ES6. The scope of var keyword is defined by the function block whereas the scope of let keyword is defined by enclosing curly braces.

If you look over the following code where we are making use of for loop, you can easily access variable number outside of curly braces when you are using var keyword, but with let, you will get undefined.

 

2. When you make use of var keyword for redeclaring same variable, you will not get any error, but that’s not the case when you make use of let. If you try to redeclare same variable with let, you will get syntax error.

Try to run the following code.