-1

I've noticed that the following results hold:

1 in [1,2,3] == true
['a','b','c'].includes('a') == true

But

'a' in ['a'] == false

This happens in both node and the browser.

Why? Can someone link me an article to read more about it?

acenturyandabit
  • 1,188
  • 10
  • 24
  • 1
    `in` checks if *the key* exists, not the value. – VLAZ Apr 02 '20 at 11:55
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in – mplungjan Apr 02 '20 at 11:56
  • aaaahh. Because I chose 1,2,3 it worked, becuase the array was 1 long. HAHAHAHA – acenturyandabit Apr 02 '20 at 11:57
  • Thanks guys, updoot for you both – acenturyandabit Apr 02 '20 at 11:57
  • 1
    It just happen to work for int, it was never supposed to work or be used for arrays. 1 in ['a','b','c'] certainly returns true also – Laurent S. Apr 02 '20 at 11:57
  • I'm certain there is a near exact dupe of this but the damn search doesn't want to cooperate. `in` is very hard to find, since it's too short... – VLAZ Apr 02 '20 at 12:01
  • Hey, same. I did a phat search beforehand. :3 – acenturyandabit Apr 02 '20 at 12:01
  • @Rajesh hahaha, I just found it and came back to link it and you've closed it seconds before me :D I *knew* I've seen that question, so I had to dig. – VLAZ Apr 02 '20 at 12:05
  • aight, fair enough, but mine has a string heheh. I hope this stays on the record anyways :D – acenturyandabit Apr 02 '20 at 12:06
  • 1
    @VLAZ I went to search for some reference material that would help make my answer better but found this... Funny world – Rajesh Apr 02 '20 at 12:07
  • 1
    @Thornkey yeah, I thought the other one had a string, too. Seems I was wrong. Still - no worries, having duplicates is a good thing, since it makes the canonical Q&A easier to find. Something that really frustrated me, since I found [another question for this](https://stackoverflow.com/questions/33505144/in-operator-issue-in-javascrip) while searching but it wasn't linked, so it was even harder to find the one with more answers and better explanation. – VLAZ Apr 02 '20 at 12:23

1 Answers1

-1

The experiment worked but only coincidentally. The key 1 existed in the array because the array happened to be 3 items long. So, the below wouldn't work:

4 in [4,5] == false

And the below would work:

1 in ["a","b"] == true
acenturyandabit
  • 1,188
  • 10
  • 24