Tom Brock
Tom Brock

Reputation: 950

What is the simplest way to print a counter after a loop has finished?

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

Answers (2)

gurvinder372
gurvinder372

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

Faly
Faly

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

Related Questions