1

I was very surprised to find out that:

> 'a' in ['a', 'b']
false
> ['a','b'].includes('a')
true

What does each command perform in NodeJS?

Ran Turner
  • 14,906
  • 5
  • 47
  • 53
yuvalm2
  • 866
  • 2
  • 10
  • 27
  • [Why does javascript's "in" operator return true when testing if 0 exists in an array that doesn't contain 0?](https://stackoverflow.com/q/3067072) | [In operator issue in JavaScript](https://stackoverflow.com/q/33505144) | – VLAZ Nov 20 '21 at 13:37

2 Answers2

1

This is not node specific but ECMA (JS) specific.

in Operator

Checks the existence of key in the collection (similar to hasOwnPropertybut also check inherited keys in prototype chain)

includes method of Array (introduced in ES6)

Checks the existence of value in the collection

Aquib Vadsaria
  • 350
  • 4
  • 9
1

Array.includes() checks for the existence of a certain value in an array, while the in operator checks for the existence of a key in an object (or an index in the case of arrays like you're describing).

console.log('a' in ['a', 'b']); // false, no such key
console.log(0 in ['a', 'b']); // true, 0 is a key that exists
console.log(1 in ['a', 'b']); // true, 1 is a key that exists
console.log(2 in ['a', 'b']); // false, 2 is a key that doesn't exists
Ran Turner
  • 14,906
  • 5
  • 47
  • 53