1

I was trying to get the total of iterations in a for loop on Javascript using node.js. Here is my code

var sum = 0;
for (itr=1; itr<=5; itr++) {
    var lt = 8;
    var sum = sum+lt;
    console.log(sum);
}

So what I get here is a list of values as the output. How do I get the last value (the total of all iterations) 40 as a single output. Can someone please guide me through this?

1 Answer 1

2

Just move console.log(sum) outside your loop. Like this

var sum = 0;
for (itr=1; itr<=5; itr++) {
    var lt = 8;
    var sum = sum+lt;
}
console.log(sum);

BTW, two possible improvements:

  1. remove the var in var sum = sum+lt;
  2. make your iteration variable var, like this: for (var itr=1; itr<=5; itr++) {
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.