displayed result exceeding the condition

Asked

Viewed 33 times

3

I have the following code snippet:

var num = 0;
while (num <= 12) {
  console.log(num);
  num = num + 2;
}

checking here now when posting the doubt, I saw that the result counts up to 12, but testing in my browser console the result is displayed up to 14.

I didn’t understand.

P.S.: I am learning!

  • This question is duplicate, I just didn’t find the other question :)

1 answer

4


The 14 that is displayed is not your product console.log, and yes the result of the last statement of while.

See what happens when you add the results into an array:

var num = 0;
var numbers = [];
while (num <= 12) {
  numbers.push(num);
  num = num + 2;
}

console.log(numbers);

It makes the iteration correctly, displaying up to the 12.

What happens is that your browser console displays the result of the latter statement in the standard output. Stackoverflow’s snippet only displays what actually went to the standard output by console.log.

Take the following test:

var num = 0;
while (num <= 12) {
  console.log(num);
  num = num + 2;

  console.log("Próximo...");
}

See that on your console, the 14 stopped appearing, but now you see undefined after the 12. This is the result of console.log("Próximo...").

Realize the value of num after all is 14, but he’s not captured by console.log to get out of while!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.