CODEMONDAY
Published in

CODEMONDAY

JavaScript: Dangerous ‘in’ keyword

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

--

--

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