-7
var a = 0;
for(b=1; b<=5; b+=a) {
document.write(b);
a++;
}

Why the output of this code is 124?

Blayke
  • 79
  • 1
  • 10
  • 3
    Try using a [debugger](https://developers.google.com/web/tools/chrome-devtools/) and go through the code execution step by step. – Bergi Dec 02 '18 at 18:22
  • Also [don't use `document.write`](https://stackoverflow.com/q/802854/1048572), try `console.log` instead. And I'd suggest printing a space after each `b` so that you can distinguish the individual outputs - it's `1`, `2`, `4`, not `124`. – Bergi Dec 02 '18 at 18:23
  • Add document.write('
    '); after document.write(b); then it will be 1,2,4.
    – Hanif Dec 02 '18 at 18:24
  • You should read this on the [Addition Assignment operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Addition_assignment) `+=`. It will help shed some light on your issue. – Russell Jonakin Dec 02 '18 at 18:28
  • Usually, in a loop, the loop counter is not touched. It automatically increments by 1 on its own (or by whatever "step" is specified). But in this example, the loop counter (b) is fiddled with and so its value changes twice in each loop. Once the automatic +1 that is built into the for loop, but that is then over-ridden by the b+=a – cssyphus Dec 02 '18 at 18:32

2 Answers2

2

Just do a dry run . When it enters into loop.

1st iteration : a = 0 , b = 1 hence prints 1
2nd iteration : a = 1 (due to a++) b = 2 (b = 1 + 1) hence prints 2
3rd iteration : a = 2 (due to a++) b = 4 (b = 2 + 2) hence prints 4
Now before going to 4th iteration b is updated to 4+3 = 7 which do not satisfy the loop condition and thus comes out of iteration and execution ends.

1

The assignment b += a is short for b = b + a. The values for b during the iterations are:

  • 1st iteration: b = 1
  • 2nd iteration: b = b + a = 1 + 1 = 2
  • 3rd iteration: b = b + a = 2 + 2 = 4

And then b is incremented to 7 <= 5 and the loop is ended.

Kristian Salo
  • 188
  • 2
  • 8
  • 2
    this is shaping up to be a good answer Kristian. Can you please answer the question though? **Why the output of this code is 124?** You've assumed the OP has the same reference as you do. Please explain the comment above from Hanif. – Randy Casburn Dec 02 '18 at 18:27