In the code below, I have declared variable i
on for loop , and trying to access variable i
and I can get the last updated value of i
, how.
for(var i = 0; i <= 10; i++){
console.log(i);
}
console.log(i,'outside');
In the code below, I have declared variable i
on for loop , and trying to access variable i
and I can get the last updated value of i
, how.
for(var i = 0; i <= 10; i++){
console.log(i);
}
console.log(i,'outside');
The var
statement declares a variable in the scope of the current function, not the current block (which is what the let
statement is for).
After the for
loop, you are still in the same function, so the variable still exists (with whatever value it was last set to).
(NB: For the purposes of var
, the code which runs outside of any function is effectively treated as being in a function of its own).
Well, you are using var
, and that's exactly a var
type should do!
We have var
and let
, let's see how they work.
when you declare your variable like this :
let something;
You only access something
in that very scope (for example your own for
loop), and outside the scope, you cannot have it. On the other hand, when you are using var
type, like this :
var something;
You are able to use this variable outside the scope ( again like your own for
loop )
Notice that we are not talking about global variables. we are just talking about scopes.
If you rather declare a global variable, just use var
in the global scope.