0

Why does the if else if else not work

I tried to "if" multiple things ( if a = 1 or 2, do something) i tried this code var input=prompt(""); if (input === "hi", "bye"){ console.log("1"); } else if (input === "yo", "hey"){ console.log("10"); } else { console.log("0"); } note: i already tried if (input = / == / ===) for the more visual thinkers and to test your solution: https://code.sololearn.com/WZ6kZfN2UqHH/?ref=app

17th Apr 2018, 8:57 PM
Roel
Roel - avatar
6 Answers
+ 1
To avoid long if statements and keep them clear you can store your values in array and check if the value exists there. var array = ["hi", "bye"]; var array2 = ["ey", "yo"]; var input = prompt("enter a word"); if(array.indexOf(input) > -1) { console.log("1"); } else if(array2.indexOf(input) > -1) { console.log("10"); }
17th Apr 2018, 9:33 PM
Toni Isotalo
Toni Isotalo - avatar
+ 1
There were a couple of mistakes, basically on the if statement. When you must test a value of a variable the right syntax is ==. Plus, if you got to test if if a variable is this OR that value the correct syntax for the OR test is ||. Here’s the correct code: function func(){ var input = prompt("enter a word"); if (input == "hi" || input == "bye"){ console.log("1"); } else if (input == "ey" || input == "yo"){ console.log("10"); } else if (input == "bonjour" || input == "hoi"){ console.log("11"); } else { console.log("0"); } }
17th Apr 2018, 9:17 PM
Luigi
Luigi - avatar
+ 1
1. I am testing a string 2. Is there really no shorter way, because I have to test for about 16 numbers and give the same output, so do I have to write " input === "string" ||" 16 times in one if statement?
17th Apr 2018, 9:23 PM
Roel
Roel - avatar
+ 1
I’ve tested my code and works fine, in 20 years of development I’ve never ever used a sigle time the === test :) It really depends, maybe it’s the case to use the “switch” statement.. (and remember the “break;” at the end on any single case!)
17th Apr 2018, 9:31 PM
Luigi
Luigi - avatar
+ 1
Thanks all for the answers, but I marked the shortest answer as the best, but all of you, thanks
18th Apr 2018, 5:46 AM
Roel
Roel - avatar