JavaScript

Check array membership with includes

Use Array.includes when you need a boolean answer about whether an array contains a value. It is clearer than comparing an index against minus one when the index itself is irrelevant.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const values = [0, NaN, "2"];
console.log(values.includes(NaN));
console.log(values.includes(2));
console.log(values.includes("2"));

How it works

Includes can find NaN and distinguishes numbers from strings. The operation examines values rather than applying a predicate, so object membership depends on the same object reference being present. For property-based matching, use some or find instead.

Limits and mistakes

Repeated membership checks over a large array may justify constructing a Set once. Do not rebuild that set for every lookup. Also distinguish sparse holes from deliberate missing values if your input can contain sparse arrays.

Check the result

Expect true, false, true. Test the exact types your import pipeline produces. If you compare objects, verify the difference between a stored object and a separately created lookalike.

Sources

Reference documentation for the behavior used in this guide: