Lessons · JavaScript · is it in there
Is it in there?
array.includes(x) and string.includes(sub) answer yes or no; indexOf gives the position or -1.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Allow-lists, feature flags, 'did the user pick this', search boxes: membership is a daily question.
How to think about it
Do I need yes/no, or the position? If you only need yes/no, includes reads best. If you need the position, indexOf. For many checks against a big list, build a Set first.
Worked example
const roles = ["admin", "editor"];Two roles.
roles.includes("editor")true.roles.indexOf("viewer")-1: not found."hello".includes("ell")true: substrings too.Your turn
Reject a name that is on the banned list.
if (banned.(name)) return false;
Solve one with the tests running
The trap
includes uses ===, so it finds NaN but never an object equal by contents. Two {a:1} objects are not the same object.
Practise is it in there on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.