How does the in operator work with sets in JavaScript?

Viewed 140

Why does the following code:

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

return false?

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

1 Answers

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

Related