JavaScript: Dangerous ‘in’ keyword

tanut aran
CODEMONDAY
Published in
2 min readMay 12, 2020

If you’re programming in Python, the normal behavior of inkeyword looks like this.

python3
>>> 'hello' in ['hello', 'world']
True

Real life scenario

Working on python and back to JS world then write the code with simple ‘if’.

JavaScript
...
word takes user input
...
lists = ['foo', 'bar']if (word in lists) {
// Expect to be here
// but never been here
}

Why the code inside if block never run?

This is dangerously JavaScript fails silently because

'foo' in ['foo', 'bar']
> false

What!!!

The correct one is includes keyword

['foo', 'bar'].includes('foo')
> true

and in is for object

'foo' in {foo: 'a', bar: 'b'}
true

Dangerous slip and hard to find

You might think use strict or TypeScript would help but it’s not.

Why?

Because in JavaScript Array is an object with numbered key

1 in ['foo', 'bar']
> true

What!!!

This can make you extremely confuse if number is in your list.

1 in [1,2,3,4,5]
> true
> oh it's work.
No, it's not0 in [1,2,3,4,5]
> true
> wait .. why?

Because the Array is an object with numbered key.

Nothing we can do about this. We have to be warned about this.

Cheers

Web Application | Software | IoT

www.codemonday.com

--

--