Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why doesn't the "===" strict equal sign work with the while() loop?

Hi, in the while loop course Dave McFarland used a strict not equal to operator. I copied the code and tried it out in my own code editor and changed the signs to see what sort of results I would get.

When I changed the code to the = equal sign, no matter what I typed if kept asking for the password again. Not even cancel would remove the alert box. It's like it was stuck in an infinite loop.

When I used the double equal == any thing I typed produced the correct answer. I got the same thing when I used the strict equality sign.

The only time it worked well was with the strict NOT equal sign.

My question is why does it only work when it is NOT equal. Why can't we compare for when it's equal to?

var secret = prompt("What is the secret password?");

while(secret !== "sesame") {
  secret = prompt("That's not it! Try again");
}

document.write("You know the secret password. Welcome.");

1 Answer

Sounds like the while() loop is working properly.

When I changed the code to the = equal sign, no matter what I typed if kept asking for the password again. Not even cancel would remove the alert box. It's like it was stuck in an infinite loop.

Yep - if you use an assignment operator ("=") in the conditional it will always be true and be an infinite loop.

When I used the double equal == any thing I typed produced the correct answer. I got the same thing when I used the strict equality sign.

The while() loop will only execute if the condition is true. Did you try typing in "sesame" - that would evaluate to true and the code within the while loop would execute.

The only time it worked well was with the strict NOT equal sign. - didn't need to be strict - but again, consider what values would result in a true vs. false value.

My question is why does it only work when it is NOT equal. Why can't we compare for when it's equal to?

That's just how this use case is set up. The idea is that you want to continue to prompt for a new password until the correct one ("sesame") is entered, then you break out of the loop and go on to the next statement which is the correct message. The condition will evaluate to true unless the variable secret is equal to 'sesame'.