Difference between “var” and “let” in JavaScript
Understanding var
Right off the bat, let’s take an example here
for (var i=0; i<10; i++){ console.log('i is: ' + i); }
Here I have declared var i as the for loop counter but an important consideration here is the scope of this variable i. If you take a moment and think closely, it’s part of the enclosing scope (which in this case is the global scope) and not that of the for loop itself. In order to test this premise, lets look at the following line of code (to be executed after the execution of the for loop mentioned earlier):
console.log('i outside of the for loop is: ' + i);
its output is:
i outside of the for loop is: 10
Whoa? Exactly, as this doesn’t happen in some of the other programming languages such as Java.
This behavior is dangerous especially if the developers tend to use and reuse already declared variables and they don’t have solid understanding of how the scope works in JavaScript.
Let’s expand this example a little further, consider the following:
var check = true; if(check){ for (var i=0; i<10; i++){ console.log('i is: ' + i); } } console.log('i outside of the for loop is: ' + i);
Just by looking at the code, it appears that the last line should throw the ReferenceError since var i is declared in the scope of the “if” block but wait, this code still works, try it out.
Why? This piece of code behaves exactly the same way as the one before because JavaScript doesn’t support block scopes. This is an important consideration.
How to get around this ungainly JS behavior? Luckily in ES6 we can now declare variables using the “let” keyword.
Enter let As already mentioned, it lets the developer declare variables just like var but it goes on up on var i.e. it attaches the variable to the scope it’s contained in hence achieving the missing block scoping.
Let’s refactor the existing example with “let”
for (let i=0; i<10; i++){ console.log('i is: ' + i); } console.log('i outside of the for loop is: ' + i);
In this case, you will get the ReferenceError instead as “i” isn’t accessible outside the scope of the for loop.
Besides, you can also create any scope (code inside the curly braces {}) and attach variables to it.
Yet another example
{ let somevar = 'some value'; console.log('some var inside the block scope: ' + somevar); } //console.log('some var outside the block scope: ' + somevar);
In the above code snippet, I have declared a variable by the name of somevar inside a block scope (pay attention to the curly braces). Its accessible only inside the given scope and not outside (as can be confirmed using the console.log statement inside the scope which works but the one outside doesn’t work when the comments are removed and a ReferenceError is encountered instead).
Bonus, the const keyword.
It’s the same as let but once declared its value cannot be changed thereafter in the code.
Here’s an example:
const pi=3.14; pi = 6.26; //TypeError: Assignment to constant variable.














