var a = 0;
for(b=1; b<=5; b+=a) {
document.write(b);
a++;
}
Why the output of this code is 124?
var a = 0;
for(b=1; b<=5; b+=a) {
document.write(b);
a++;
}
Why the output of this code is 124?
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.
The assignment b += a
is short for b = b + a
. The values for b during the iterations are:
b = 1
b = b + a = 1 + 1 = 2
b = b + a = 2 + 2 = 4
And then b is incremented to 7 <= 5
and the loop is ended.
'); after document.write(b); then it will be 1,2,4. – Hanif Dec 02 '18 at 18:24