Difference between var and let in javascript. All you need to know

For training and consulting, please write to us at info@xrmforyou.com
And here I am back with a common question that is asked to me by an beginner who is trying their hands out with javascript.
After all both var and let are used to declare variables in JavaScript. Well the difference between them is – var is function scoped and let is block scoped.
Come on! Show me some code.
image
Let’s start with a simple example here.

console.log(var1);
var var1 = 20;
console.log(var1);

And then let’s see the output in the console window.
image
Observe the output here. The first result gives us undefined and the second result gives us the value of variable as defined.
The first console.log statement tries to access the variable even before the variable is declared.
Now let’s do something else.
image
Here I am trying to access the value of a random variable which is not even declared. Observe you get an error here and not undefined. And you may ask what is the difference between first and second example. In both the examples, I tried to access a variable value before it is being declared. But one gave me error and the other gave me undefined.
In the first example, the variable was eventually declared after the first console.log statement. Since it was declared using the var keyword, when the first line executed, the runtime know there is a variable declared in the next step but at the moment it is undefined. And that’s what makes var keyword interesting.
Now let’s repeat the first example with let instead of var.
image
See here now. With let, the variable is only scoped to the block in which it is declared. So now for the runtime, the scenario is equivalent to our second example. var2 is only available in the block post it is declared. It got an exception and the second statement didn’t even execute.
Hell yeah! Tiny little things are so interesting.
Hope this helps!
Debajit Dutta
(Microsoft Business Solutions MVP)


Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe to get the latest posts sent to your email.

Discover more from Debajit's Power Apps & Dynamics 365 Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading