-1

I am learning JavaScript for loop where I tried running this code in google chrome developers tools where the output made me more confused. Can someone explain me what this code is doing.

let sum = 0;
for (let i = 2; i <= 6; i++) {
    sum = sum + i;
}

I was expecting the result as 6, as the "test condition" given is i <= 6 but I got the output as 20. How I am getting 20 here when the loop has to stop at 6

5
  • 4
    It sums up all the values of i, and 2 + 3 + 4 + 5 + 6 is 20 Commented Mar 18, 2020 at 10:17
  • 3
    If you want sum to read 6, you should increment by 1 at every iteration, i.e. sum++ instead of sum + i. Commented Mar 18, 2020 at 10:19
  • 3
    @Terry: That should provide 5 since it starts at 2. Commented Mar 18, 2020 at 10:24
  • If OP changes let i = 1; i <= 6 or let i = 0; i < 6 in conjunction with using sum++ then that will work Commented Mar 18, 2020 at 10:24
  • Yes it would.. naturally if one changes everything the output gets different. Commented Mar 18, 2020 at 10:25

2 Answers 2

2

It doesn't adds 1 in each iteration it adds the value of i which increase in each loop.

sum = 2 + 3 + 4 + 5 + 6 

You can see what's happening in your code in the below snippet

let sum = 0;
for(let i = 2; i <=6; i++){
  sum = sum + i;
  console.log(`sum = ${sum - i} + ${i} = ${sum}`)
}
console.log(sum)

If you will increment sum by 1 and start loop at 1 instead of 2 then the result value will be 6

let sum = 0;
for(let i = 1; i <=6; i++){
  sum = sum + 1;
}
console.log(sum)

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for clear explanation, I was looking for this... now I understood how Javascript works in for loop.
@Zeba Consider accepting the answer if you thinks it best for you.
1

in 1st line, you have assigned sum as initially zero. for loop, the loop will start with taking initial of i i.e 2 and stop when it is 6 i.e i<=6

i = 2 .... sum = sum + i; ... sum = 0 + 2 = 2

i = 3 .... sum = sum + i; ... sum = 2 + 3 = 5

i = 4 .... sum = sum + i; ... sum = 5 + 4 = 9

i = 5 .... sum = sum + i; ... sum = 9 + 5 = 14

i = 6 .... sum = sum + i; ... sum = 14 + 6 = 20

so your final output is 20

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.