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;
}
4
  • 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: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide Commented Aug 20, 2014 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. Commented Aug 20, 2014 at 22:39
  • 2
    That's why it's good to learn from multiple sources. Commented Aug 20, 2014 at 22:39
  • Yeah, that's a good idea. Thanks for the link. Commented Aug 20, 2014 at 22:41

2 Answers 2

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much. That fixed it and helped me clear up the difference between those two.
Also, can you explain to me what === is? Is it any different?
@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.
@SpencerWieczorek: I assume "make both sides the same" means "converting both values to the same data type".
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.