1

Why does this return false?

var flavor = "chocolate";
console.log(flavor == ("vanilla" || "chocolate")); 

and if I type instead:

var flavor = "chocolate";
console.log(flavor == ("vanilla" && "chocolate"));

it returns true. This doesn't make sense to me because logically, flavor cannot equal both chocolate and vanilla. Can someone help me understand how I should be thinking through this?

phuclv
  • 37,963
  • 15
  • 156
  • 475
Nathan Ong
  • 13
  • 2
  • Possible duplicate of [Javascript: The prettiest way to compare one value against multiple values](https://stackoverflow.com/questions/9121395/javascript-the-prettiest-way-to-compare-one-value-against-multiple-values) – david Mar 07 '18 at 01:59

1 Answers1

0

(flavor == ("vanilla" || "chocolate")) returns false because ("vanilla" || "chocolate") returns as "vanilla", so you're actually comparing "chocolate" == "vanilla", which returns false.

(flavor == ("vanilla" && "chocolate")) returns true because ("vanilla" && "chocolate") returns as "chocolate", so "chocolate" == "chocolate" obviously returns true.

I think what you actually want is (flavor == "vanilla" || flavor == "chocolate") and (flavor == "vanilla" && flavor == "chocolate"). Give that a try :)

sykez
  • 2,015
  • 15
  • 14