Published in


JavaScript: Dangerous ‘in’ keyword

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

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

Real life scenario

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

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


The correct one is includes keyword

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

and in is for object

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

Dangerous slip and hard to find

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


Because in JavaScript Array is an object with numbered key

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


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.


Web Application | Software | IoT



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store