Reputation: 53
Can someone explain that why the value of i
with the var
keyword changes after re-declaring the same variable in a for
loop?
For example the value 10
is set to variable i
and after setting the condition in for loop i < 40
the value changes to i?
var i = 10;
for (var i = 0; i < 40; i++) {
// code block
}
document.getElementById("demo").innerHTML = i;
<div id="demo"></div>
Upvotes: 0
Views: 65
Reputation: 29
Because in the first part of your loop, you are re-declaring the same var.
To solve this, you must change the name of the first "i" var. For example "j"
And on the first part of your loop, equal "i" to "j" -> var i = j
Here is the snippet
var j = 10;
for (var i = j; i < 40; i++) {
// code block
}
document.getElementById("demo").innerHTML = i;
<div id="demo"></div>
Upvotes: 2
Reputation: 944169
var
statements are scoped to the function they are declared within and the for
loop is in the same function as the line immediately before it. (For historical reasons, redeclaring a variable with var
doesn't throw an error, it is just silently ignored (although the assignment isn't).)
Use a let
statement if you want a variable scoped to the block.
Upvotes: 4