Reputation: 950
If I run the following code it will output 0
.
var total = 0;
for(var i = i; i <= 100; i++) {
total = total + i;
}
console.log(total);
This is because the line console.log(total)
doesn't wait for the loop to finish; it just immediately executes.
How can I print the final value of total?
Upvotes: 2
Views: 325
Reputation: 68413
Change for loop to
for(var i = 0; i <= 100; i++) { //i=0 instead of i = i
i = i
will cause i = undefined
and that will cause i < 100
to fail
Upvotes: 3
Reputation: 13356
There is a mistake in your code:
change:
for(var i = i; i <= 100; i++)
To:
for(var i = 0; i <= 100; i++)
And it works:
var total = 0;
for(var i = 0; i <= 100; i++) {
total = total + i;
}
console.log(total);
Upvotes: 4