For loops as part of an if/else statement


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-NhsaT/2/5?curriculum_id=506324b3a7dffd00020bf661


I'm trying to combine some of the things I've learned in the last part of the loops exercise, including a prompt, if/else statements, and a for loop. I wanted to put the for loop inside of an "if" statement, but it executes the loop regardless of whether the "if" condition is true or not. Can I put a for loop inside of an if/else statement, and if so, what did I do wrong?


var colors = ["red", "green", "blue", "yellow", "purple"];
var userChoice = prompt("Do you like colors? Yes or no?");
if (userChoice = "yes") {
    for (i = 0; i < colors.length; i++) {
        console.log("I like the color " + colors[i])
    }
} else {
    console.log("I don't like colors")
}


#2

Comparison uses === to test identity.


#3

Thanks! That was it. I have a new question though. I wanted to make it where other affirmative answers from the prompt will be acceptable. So the user can also answer yep, or yeah, etc. I've found how to make the prompt answers not case sensitive. But when I add those additional versions of "yes" using "||" it again causes it to run the "if" loop regardless of the prompt answer. And if I use "|", it always returns the else statement. How can I get it to work?

EDIT: Nevermind, I realized that I need to use "userChoice ===" each time. But is there a way to make that more succint, like if I wanted to put in a lot more variations of the word "yes"?

var colors = ["red", "green", "blue", "yellow", "purple"];

function colorAsk() {
    var userChoice = prompt("Do you like colors? Yes or no?");
    return userChoice.toLowerCase();
}
var userChoice = colorAsk();

if (userChoice === "yes" || userChoice === "yeah" || userChoice === "yep") {
    for (i = 0; i < colors.length; i++) {
        console.log("I like the color " + colors[i])
    }
} else {
    console.log("I don't like colors");
};

#4

The interpreter treats this differently than we might at first assume. We see the above as,

if userChoice is "yes" or "yeah" or "yep"

and have no problem in our own mind interpreting this as one or the other. Not so for the JS interpreter. Consider,

// LET u = userChoice  for brevity
u = userChoice
if (u === "yes" || u === "yeah" || u === "yep") {

}

Each operand in the logical expression is a complete expression.

Something to consider about truthiness...

A non-empty string evaluates to true. A non-zero number evaluates to true.

userChoice === "yes" || "yeah" || "yep"

Let's say userChoice is NOT "yes" The above will look like this to the interpreter...

false || true || true

which evaluates to true. Not what we expect, is it?

Okay, I see you edited the post. Leaving this up, anyways.


#5

Yeah, I figured out what was wrong, but not necessarily why. So your explanation is still quite helpful, thanks!


#6

Yes there is. Several, in fact. Consider,

The in operator.

if (userChoice in ["yes", "yeah", "yep"]) {

}

String.match(regex) method:

console.log(!!"no".match(/no|nope|notta/));

"no".match(/no|nope|notta/)  yields  [ 'no', index: 0, input: 'no' ]

NOTting it once converts to a boolean, false, the second time negates to true.

Array.indexOf() method:

This will return -1 if no match is found, else it will return the index.

if (["yes", "yeah", "yep"].indexOf(userChoice) > -1) {

}

Another regex method

var re = /no|nope|notta/;
re.test(userChoice)

returns true or false.

On another note, what will this return if the user clicks Cancel or presses the Esc key?


#7

Awesome, thanks! I'm still new to this. There's so much to learn!

I didn't think about if the user clicks cancel. It returns "TypeError: Cannot read property 'toLowerCase' of null". Is there a better way of making it not case sensitive, or something additional I need to add so that it doesn't return an error?


#8

This is a subject I've raised a number of times over the years. Search the forums for 'prompt() returns null' to ferret them out.

Briefly,

    var user = prompt("...");
    if (user !== null) {
        // code here
        user = user.toLowerCase();   // a string so has the toLowerCase property
    } else {
        console.log("Bye!");
    }

#9

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