
Difference between VAR LET and CONST in JavaScript

Hi, do you want to understand the difference between var, let and const variables? Then you can read this post to completely understand how these variables work in JavaScript.
Difference between VAR, LET and CONST:
VAR: If you declare a variable with var
keyword then you have the ability to update and re-declared it.
LET: If you declare a variable with let
keyword then you have the ability to update it but you can’t re-declare it.
CONST: If you declare a variable with const
then you can’t updated and re-declare it.
var
and let
keyword are very similar when used outside of a function block but global variables defined with let
will not be added as properties on the global window object like those defined with var
.
I will give you three examples to make you understand about var
, let
and const
variables. You will need the copy the given code and try the examples on your system for better understanding.
Example 1:
<script> var x = 5; let y = 5; console.log(window.x); // ok console.log(window.y); // undefined </script>
The above example will notice that you are getting an undefined variable error for let y = 5;
because it is not added on the global window object. But var x = 5;
is available on global window object.
Example 2:
<script> for (var i = 1; i < 6; i++) { console.log(i); } console.log(i); </script>
The above example will work perfectly as we have used var
. You can see that we have tried to access the i
variable outside the for()
loop and we are getting the value without any error.
Example 3:
<script> for (let i = 1; i < 6; i++) { console.log(i); } console.log(i); </script>
Above code will give you the following error Uncaught ReferenceError: i is not defined
if you try to access i
variable outside the for()
loop. Because let
is only visible in the for()
loop if declared inside the for()
loop.
Hope you understand the difference.
Thanks for visiting.