Today I tried shortening an if statement like this:
if (fruit == "apple" || type == "pear" || type == "orange"){
to this:
if (fruit in ["apple", "pear", "orange"]){
It doesn’t work. Jonathan Snook has a different solution here where he essentially uses a map like this, which does work:
if(fruit in {"apple":"", "pear":"", "orange":""}){
Why does that work and my simple array doesn’t, when usually in Javascript an object’s presence makes that object return true? Is a string a different type of object than a key? I thought the string’s presence in my array would return true as well.
y = "Stackoverflow";
y && console.log('y is true') // y returns true, so console logs the message
I interpreted my original solution as “if the value of variable fruit is in this array.” That’s clearly not the case. Does it instead say “if the variable fruit itself is in this array?” No, because this doesn’t work either:
if (fruit in [fruit, "apple", "pear", "orange"]){
So what is Snook’s version with the key=>value map asking that’s correct? My best guess is, “if a key under the name of the value of variable fruit in this map returns true?”
x in yreturnstrueif the objectyhas a property with namex(so yes, your guess is correct).Arrays are objects too. The properties of an array are the indexes, which are numerical †. This works:
because the array has an element at index
0. This array is similar (but not the same!) to this object:(of course an array has further properties like
length,push,slice, etc)In your object example (
{"apple":"", "pear":"", "orange":""}),apple,pearetc. are the properties of the object, not the values of properties.How to find out whether an element is contained in an array is described in How do I check if an array includes an object in JavaScript? .
†: Strictly speaking, every property is a string, so even if you use numbers (as it is the case with arrays), they are converted to strings.