displayed result exceeding the condition

3

I have the following code snippet:

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

Checking here now at the time of posting the doubt, I saw that the result counts until 12, but testing in the console of my browser the result is displayed until 14.

I do not understand.

Q: I'm learning!

    
asked by anonymous 07.08.2018 / 00:17

1 answer

4

The wc% that is displayed is not the product of its% wc, but the result of the last statement of% wc%.

See what happens when you add results to an array:

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

console.log(numbers);

It iterates correctly, displaying up to 14 .

What happens is that your browser console displays the result of the last statement on standard output. The StackOverflow snippet only displays what actually went to 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...");
}

Notice that on your console, while stopped appearing, but now you see 12 after console.log . This is the result of 14 .

  

Notice that the value of undefined after all is 12 , but it is not caught by console.log("Próximo...") by exiting num !

    
07.08.2018 / 00:27