2

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;
}
Tim
  • 315
  • 4
  • 23
  • I'm curious, why did you think that `=` would behave differently in different locations? I recommend to read the MDN JavaScript Guide to learn the basics: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide – Felix Kling Aug 20 '14 at 22:34
  • I'm using Codeacademy to learn Javascript and it never mentioned that = and == are used differently. I just assumed they were interchangeable. – Tim Aug 20 '14 at 22:39
  • 2
    That's why it's good to learn from multiple sources. – Felix Kling Aug 20 '14 at 22:39
  • Yeah, that's a good idea. Thanks for the link. – Tim Aug 20 '14 at 22:41

2 Answers2

4

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.
Timeout
  • 7,759
  • 26
  • 38
  • Thank you very much. That fixed it and helped me clear up the difference between those two. – Tim Aug 20 '14 at 22:31
  • Also, can you explain to me what === is? Is it any different? – Tim Aug 20 '14 at 22:33
  • 1
    @Tim `===` is strict comparison. While `==` will attempt to make both sides the same data type, `===` will not. so `1 == "1"` works while `1 === "1"` does not. – Spencer Wieczorek Aug 20 '14 at 22:35
  • 1
    @SpencerWieczorek: I assume *"make both sides the same"* means "converting both values to the same data type". – Felix Kling Aug 20 '14 at 22:36
3

= 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
Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54