Using variable values as answers to prompts in if/else statements which include logical operators, in JavaScript


#1

When I answer the prompts using the values of the variable 'positive' ('yes','absolutely','definitely') I would like it to print "Great". However, it prints '!!!' instead (the printed answer for the else statement).

Here is the code in JavaScript:

var positive = ('yes','absolutely','definitely')

var answer1 = prompt("Do you like sport?");
var answer2 = prompt("Do you play sport?");
{
if(answer1 == positive && answer2 == positive) {
console.log('Great');
}
else if (answer1 == positive && answer2 == !positive) {
console.log("Perhaps you should!")
}
else if (answer1 == !positive && answer2 == positive) {
console.log("Why do you play sport if you don't like sport?")
}
else {
console.log("!!!")
}}


#2

this is not how javascript works, a string which contains yes, absolutely and definitely will never equal a string which contains just a part of the string.

make positive an array, loop over the array to check if the user inputs equals one of the options in your positive array


#3

I've made positive an array:

var positive = ['yes','absolutely','definitely'];

and have created my loop:

for (var i = 0; i < positive.length; i++);

but I'm stuck on how to check if the user input equals one of the options in the array. Any help please


#4

sorry, my mistake. I am so sorry. Javascript has build in support for this:

var positive = 'yes absolutely definitely'
if (positive.includes(answer1) && positive.include(answer2)){
  // do something
}

you can read more about include here


#5

Thanks a lot. That's great help!!:grin: