My if else statement only returns one case regardless of input!


#1


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

Hi all! I'm trying to properly execute an if else statement nested in my switch case with the logic: if someone enters either 'mugen' or 'jin' for companionOne and companionTwo, print out "Great..." and for all other entries print out "You got the wrong guys..." and if companionOne is the same as companionTwo ask them to choose two different people. But my code always prints out my first if condition regardless of the input! I don't know what is wrong, any help is appreciated!

var user = prompt("Do you want to find the Samurai that smells of sunflowers?").toLowerCase();
switch(user) {
    case 'yes':
        var companionOne = prompt('Who is the first person \ you want to bring on your journey?')
        var companionTwo = prompt('Who is the second person \ you want to bring on your journey?')
        var m = "Mugen".toLowerCase()
        var j = "Jin".toLowerCase()
    if(companionOne = companionTwo) {
            console.log('You have to choose two different \ people!')
        }
else if((companionOne= m || j) && (companionTwo = m||j))
        {
            console.log("Great," + companionOne + " & " + companionTwo + "may be knuckle heads, but they sure are strong, let's go!")
        }
        else {
            console.log("You got the wrong guys, find some \ better body guards!")
            }
        break;


#2

First of all your missing a couple of semicolons

your also missing } to close the switch

and the slashes mess things up

var companionOne = prompt('Who is the first person \ you want to bring on your journey?')
var companionTwo = prompt('Who is the second person \ you want to bring on your journey?')


#3

I have the final } to close the switch after my other cases, but I didn't paste those parts of the code because they work fine. I also added semicolons after each console.log but still doesn't seem to work. Should I remove the slashes? I thought you need those if your strings cross multiple lines?


#4

No, browsers only allow single-line input for prompt().


#5

Is that the reason my code doesn't execute properly? I removed the slashes and the prompt comes out just fine even though the string goes to the second line, but it still always prints out the first if condition.


#6

try adding == or === to this code

if(companionOne = companionTwo)

because doing this = changes the varibles

if you want to make something equal too write ==
and if you want it equal value or equal type write ===


#7

@billngo92:

(companionTwo = m||j)

Is that meant to compare the value in companionTwo with the logic operation OR with the variables m and j?
Because the logical operator will bring back a logical value, True or False, and you're comparing that to the user's input, which I suppose is a string.


#8

Oh right, thanks for that clarification! That fixes the first part of my if statement, but my second condition does not execute properly still (I changed it to else if((companionOne === m || j) && (companionTwo === m||j)))


#9

Well I tried to do it like that to shorten the line of code for that line, but essentially I wanted to say that companionTwo can be either the strings "mugen" or "jin" for it to be true, which I made equal to the variable m and j. Can I not do that?


#10

@billngo92: You can assign values to other variables, as far as I know, you won't write what type your variable will be but the way things are, won't work, at least from what I see.
companionTwo and companionOne seem to be two variables that will hold the inputs from the user(s) and you're trying to compare that to some other variables.

Is that okay? Yes, it is but comparing two strings with a logical operator like that m || j doesn't really seem to work, unless they're both holding logical values, True and/or False.
The idea of trying to make it short it's great, optimizing the code is always great but in this case you'll still need to compare element by element, unless there's a trick where you can compare one thing to many, maybe some arrays could help but wouldn't be necessary.

If the idea is to compare a string to another, you'll have to go one by one, sorry to say that :confused:


#11

Dont declare var in a switch


#12

I see your point! I tried to fix my code to this now, but i get an error of: SyntaxError: Illegal return statement. Why is my return statement illegal?!

switch(user) {
    case 'yes':
        var companionOne = prompt('Who is the first person you want to bring on your journey?').toLowerCase();
        var companionTwo = prompt('Who is the second person you want to bring on your journey?').toLowerCase();
        if (companionOne === ('jin' || 'mugen')) {
            return true}
        else if (companionTwo === ('jin' || 'mugen')) {
                return true}
        else {
            return false};
    if(companionOne === companionTwo) {
            console.log('You have to choose two different people!');
        }
else if(companionOne && companionTwo)
        {
            console.log("Great, " + companionOne + " & " + companionTwo + " may be knuckle heads, but they sure are strong, let's go!");
        }
        else {
            console.log("You got the wrong guys, find some \ better body guards!");
            }
        break;

#13

@billngo92: The return statement is mostly, if not only, used whenever we work with functions and that's not the case.
A switch is pretty much a big and more "complex" if-else statement.

You still want to use the return statement? Get a function and put all of that, your switch, inside of it.
Don't want to use the return statement? Erase it and use the break statement (even tho you already have one) and it will make the execution of your program to simply go to the next instruction right after your switch statement.


#14

I see, but now I switched my code to this and my else if portion still doesn't function properly! It doesn't print "You got the wrong guys..." if my input is anything other than 'jin' or 'mugen'! Sorry to drag out this problem so long, perhaps you could give me a suggestion on how to code what I want my program to do?

switch(user) {
    case 'yes':
        var companionOne = prompt('Who is the first person you want to bring on your journey?').toLowerCase();
        switch (companionOne) {
            case 'jin'|| 'mugen':
                companionOne===true
                break;
            default:
                companionOne===false
                break; }
        var companionTwo = prompt('Who is the second person you want to bring on your journey?').toLowerCase();
        switch(companionTwo) {
            case 'jin'|| 'mugen':
                companionTwo===true
                break;
            default:
                companionTwo===false
                break; }
    if(companionOne === companionTwo) {
            console.log('You have to choose two different people!');
        }
else if(companionOne && companionTwo)
        {
            console.log("Great, " + companionOne + " & " + companionTwo + " may be knuckle heads, but they sure are strong, let's go!");
        }
        else {
            console.log("You got the wrong guys, find some \ better body guards!");
            }
        break;

#15

@billngo92:

 case 'jin'|| 'mugen':


You're comparing jin with mugen but in this way it will simply ask "Is something I don't know equal/different than 'jin' ?" and "Is something I don't know equal/different than 'mugen' ?"
Both questions will end up being trued and the find condition will execute.

Okay, a condition was met on the first switch and now it will move foward to the next one.
It will make the same question again, just like the first one.

If the idea is: get some input from the user and compare if they're equal to jin and/or mugen, you'll have to go and ask if companionOne is equal to 'mujin' or companionOne is equal to 'jin': do something (this is just the idea,not the actual code).

There's not really a need for those switches, just the first one, switch(user), should be enough for it.
Get the input from the user(s) and compare each input, seperately from one another, and see if they're equal to jin or mugen.
After that, continue with the execution of your code.

In case you didn't get the idea, here's how it would work:

get input from user1
get input from user2
compare if user1's input is equal to jin  or user1's input is equal to mugen:
        do the rest of the execution in case is equal to True or False (simple idea of if-else)
compare if user2's input is equal to jin  or user2's input is equal to mugen:
        do the rest of the execution in case is equal to True or False (simple idea of if-else)
compare if user1's value is equal to user2's value [and so on]

This is the basic idea of your code.
Note: doing

companionOne && companionTwo

Might cause some issues in case those values are not boolean (True or False), you'll need to compare each one of them so they can return a logical value to later be compared with the AND operator.

(2 > 5) && (5 < 7) -> F && T -> F

If I wasn't clear, let us know and we'll find another way to explain it to you :slight_smile:


#16

I think I'm following what you're saying, but then how do I check if input for companionOne and input from companionTwo are true at the same time? For example, if I do this code:

if(companionOne === companionTwo) {
            console.log('You have to choose two different people!');
        }
else if (companionOne === 'jin'|| 'mugen')
        {
            console.log("Great, " + companionOne + " & " + companionTwo + " may be knuckle heads, but they sure are strong, let's go!");
        }
else if (companionTwo === 'jin' || 'mugen')
        {
            console.log("Great, " + companionOne + " & " + companionTwo + " may be knuckle heads, but they sure are strong, let's go!");
        }
        else {
            console.log("You got the wrong guys, find some \ better body guards!");
            }
        break;

Won't it check the second condition to be true and execute before it checks the third condition? And actually using this code, the second condition doesn't even execute properly if companionOne is something other than 'jin' or 'mugen'!


#17

@billngo92:

You'll need to compare the value stored in companionOne with the value stored in companionTwo, otherwise it might not be possible to check if they're equal, considering you're only using those two variables.

Instead of writing:

companionOne === 'jin'|| 'mugen'

write this:

companionOne === 'jin'|| companionOne === 'mugen'

The way the first one is, considering all of them are just strings and there are no logical values, might cause some issues to your program, depending on what you want to do.

Also, first compare which one they've picked , jin or mugen, to later determine if they've picked the same option or not, in other words:

if(companionOne === companionTwo) {
            console.log('You have to choose two different people!');
        }

Should actually go after validating their inputs since you need to check if one of them, or both, are equal to jin or mugen.


#18

My code works correctly if I use this!

if(companionOne === companionTwo) {
        console.log('You have to choose two different people!');
        }
else if ((companionOne === 'jin' || companionOne ==='mugen') && (companionTwo === 'jin' || companionTwo ==='mugen'))
        { console.log("Great, " + companionOne + " & " + companionTwo + " may be knuckle heads, but they sure are strong, let's go!");
        }
else {
      console.log("You got the wrong guys, find some \ better body guards!");
            }

I found that I have to check if companionOne and companionTwo are the same before I check if their inputs are valid because if I check if they are valid first and they are, the command will execute before it moves on to check if they are both the same input. Does this logic make sense? I checked my code for all scenarios and it seems to work!


#19

@billngo92: Yes, now it does makes far more sense, good job! :sunny:
Keep coding! :slight_smile:


#20

Thanks a lot @g4be I really appreciate your help!