6. Soloflight


#1


Hey

Not sure why but I think I have an infinite loop here. Can somebody tell me where I went wrong?

Thanks in advance.


//Remember to make your condition true outside the loop!
var condition = true;

var soloLoop = function(){
  while (condition = true) {
      console.log("Looped once!");
      var condition = false;
  }
 };

soloLoop();


#2

Two things. First of all, your while should be: while (condition === true). Second, when you set your condition to false it should be: condition = false. Your code makes a new variable named condition, instead of just changing the value of the old one.


#3

Thanks. What would be the difference between writing the condition as === opposed to = in this context?


#4

=== is a comparison operator. You would use it in this to check if condition is equal to true.
= is only used for setting values to variables for example:
var myVar = "string";


#5

I don't understand how the code below would be infinite because the value of condition will still change to false from the code in the while loop, and since the condition is that while is true, it should break the loop? Unless this is something to do with scopes - and having "condition = false" doesn't change the value of condition defined on the first line?

var condition = true;

var soloLoop = function(){
while (condition = true) {
console.log("Looped once!");
condition = false;
}
};

soloLoop();


#6

I tested the code:

var condition = true;

var soloLoop = function(){
    while (condition === true) {
        console.log("Looped once!");
        condition = false;
    }
};

soloLoop();

And it worked as planned. The reason it was infinite is because you were not setting the condition to false properly.


#7

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