The course is asking me to form a while loop and I keep getting errors or infinite loops. What am I doing wrong?
var understand = true;
while(understand= true){
console.log("I'm learning while loops!");
understand = false;
}
The course is asking me to form a while loop and I keep getting errors or infinite loops. What am I doing wrong?
var understand = true;
while(understand= true){
console.log("I'm learning while loops!");
understand = false;
}
You are using an assignment operator (=
) and not an equals test (==
).
Use: while(understand == true)
Or simplified: while(understand)
Update from comments:
===
means the value and the data type must be equal while ==
will attempt to convert them to the same type before comparison.
For example:
"3" == 3 // True (implicitly)
"3" === 3 // False because a string is not a number.
=
means assignment, while ==
is comparison. So:
while(understand == true)
Also note that while
and other branch structures, take conditions. Since this is a Boolean you can just use itself:
while(understand)
Also a note of the difference between ==
and ===
(strict comparison). The comparison ==
will attempt convert the two sides to the same data type before it compares the values. While strict comparison ===
does not, making it faster in most cases. So for example:
1 == "1" // This is true
1 === "1" // This is false