2

Why does the following code:

'%' in new Set('%');

return false?

And is the in operator faster on a set than on an array?

  • 1
    It works the same way as with arrays: it doesn't. – VLAZ Aug 19 '21 at 07:41
  • What part of [the documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) gave you the idea that `in` can be used with sets? – deceze Aug 19 '21 at 07:43
  • The documentation doesn't specify anything of the sort, but it might be because of [the in operator in python](https://www.askpython.com/python/examples/in-and-not-in-operators-in-python) that behaves similarly as `Set.prototype.has` and `Array.prototype.includes` in javascript – Nino Filiu Aug 19 '21 at 07:48

1 Answers1

4

The in operator returns true if the specified property is in the specified object or its prototype chain.

It does not check if something belongs to a set. You should use Set.prototype.has for that.

const obj = { someKey: 'someValue' };
'someKey' in obj; // true
'someOtherKey' in obj; // false

const set = new Set([1,2,3]);
set.has(1); // true
set.has(4); // false

Regarding performance, please refer to this question

Nino Filiu
  • 16,660
  • 11
  • 54
  • 84