While loop question


#1

Not to produce any new topics, two questions regarding this exercise:

  1. It says that JS understands 1 as true. In this case shouldn't this work? ->

while(understand === 1)

  1. While using the mentioned solution while(understand === true) it prints out "I'm learning while loops" and in another line false. Can anyone explain why? I'm not using the console.log command for it so as far as I understand it shouldn't be there. I'm attaching the full code to make it easier:

var understand = true;

while(understand === true ){
console.log("I'm learning while loops!");
understand = false;
}


While loop screen is not responsive
#2

using three equal signs also means the data type should match. 1 is a integer, true is a boolean, data type is not a match. Two equal sign means the data type don't have to be a match, so:

while(understand == 1)

would work

You update a variable after the last console.log statement, so the console displays the last updated value. If you don't want this, swap console.log and updated understanding to false lines around


#3

Stetim94, thanks for the clarification regarding 1st point, it works as you said :slight_smile:

As for the second part I know form previous lessons that when using the variable name without VAR I am updating it. However I don't understand why it prints. Does it always work like this? And how should I update the lines around? If I remove the line changing understand to false it creates infinite loop (already tested :wink:) If i move it out of the while loop it creates infinite loop again.


#4

this is console behavior, the last updated variable is logged to the console if there are no more console.log() after updating the variable

which is why i recommended swapping console.log and updating the variable around, this way, the last thing reached is a console.log, so the updated variable doesn't get logged by console behavior


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.