Home > OS >  Can someone explain this simple concept of a JavaScript loop?
Can someone explain this simple concept of a JavaScript loop?

Time:11-09

Considering this code:

var x = 3;
var i = 0;
while (i < 3) {
  x  = 1;
  i  = 1;
}
println(x);

Why would the output be 6? Can someone break it down for me?

I understand that x will continue adding 1 to it's value, but why does the i<3 limit it to 6?

CodePudding user response:

The answer will be 6 because your initial value of X is 3. You have only 3 iterations in your while loop.

i = 0 => x  1 = 4
i = 1 => x   1 = 5
i = 2 => x   1 = 6
i = 3 => exit loop

CodePudding user response:

I will explain it step by step

while loop will take values, while i is smaller than 3 right.

X starts as 3 and i starts as 0.

While checks if i < 3. (it is 0 for now ) (x =1 means x = x 1 (same for i ))

i was 0, so while loop will start working. x will become 4 and i will become 1.

second run: i is 1 still lower than 3 so while loop will keep working.

x will become 5 and i will become 2

i is still lower than 3 so while loop will keep working x will become 6 and i will become 3

now i is equal to 3 so no longer lower than 3. While loop will stop working and you will get the outputs.

But if console.log (x) was in the while loop. You will get all the x results. The output would be: 4 5 6

So, if your question is why am I getting only 6 as an output? It is because your function comes after the while loop.

CodePudding user response:

Before entering into the loop: x=3, i=0 (i is less than 3, so the condition is true)

After the first step: x=4, i=1 (i is less than 3, so the condition is true)

After the second step: x=5, i=2 (i is less than 3, so the condition is true)

After the third step: x=6, i=3 (i is not less than 3, so the condition is false)

Because the condition is false, it is exited from the loop and the value of x is printed in the output.

  • Also, println() is not defined in JavaScript. We can use console.log().
  • Related