Alvaro Joao Alvaro Joao - 1 year ago 54
Javascript Question

Javascript IN operation not working with one item array

following the snippet bellow, why an array with one position is not working properly when using


You can see that with 2 item the operation works fine.

  • Why this is happening?

  • What's the work around?

// helper function
function showResult(result) {
document.querySelector('#result').innerHTML += result+'<br/>';

var a = ["1"]
var b = "1"

showResult(b in a);

var a = ["1","2"]
var b = "1"

showResult(b in a);

<div id="result"></div>

Answer Source

The in operator checks if an object has a key, not a value. Your second case returns true because any array with two elements has keys '0' and '1'. It doesn't matter that '1' also happens to be a value in that array; '1' in ['foo', 'bar'] is also true.

To test if an element is in an array, you should use Array.prototype.indexOf or in modern engines Array.prototype.includes. You can use the polyfill from either of those links to get support for that method in all engines:

// Most engines (IE 9+)
showResult( a.indexOf( b ) >= 0 );

// Modern engines only:
showResult( a.includes( b ) );