You see, there are three possible options:
has() and I mix them up all the time. So I’m writing this for my own reference.
The main problem
The function name to use for this depends on the type of list you’re working with, even though the signature of each function is exactly the same.
You call a function on the list with the item as an argument and you end up with a boolean that tells you if the item is in the list or not:
// returns true or false
For arrays, you need to use the
classList is a
DOMTokenList, and those use
Maps (and WeakMaps) are relatively new features and act as a sort of “better” object (I won’t go into the differences in this article).
To figure out if a given key exits in a Map, you need to use
Sets (and WeakSets) are relatively new features and act as a sort of “better” array (Again, I won’t go into the differences in this article).
For Sets you also need to use
In handy table form:
|Function to use
Why is it not all the same?
Honestly I don’t know.
classList is a DOM api whereas Array, Set and Map are all language features, which could explain the difference between classList and the rest.
It still doesn’t explain why Array uses
includes and Sets and Maps use
has. I can’t think of a good reason other than oversight during API development, but maybe someone can tell me.
In any case I hope that having written this down will help me remember better, or that it will at least be a quick lookup for me.