includes Finds NaN That indexOf Misses

indexOf searches with strict equality so NaN is never found; includes uses SameValueZero and reports NaN hits, making it the right check for dirty data.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// indexOf finds elements via strict equality: NaN === NaN is false, so it never finds NaN
const readings = [1.5, NaN, 2.5];
console.log('indexOf(NaN):', readings.indexOf(NaN));
console.log('includes(NaN):', readings.includes(NaN));

// includes uses SameValueZero internally: NaN equals NaN; +/-0 count as equal in both methods
console.log('includes(-0 in [0]):', [0].includes(-0));
console.log('indexOf(-0 in [0]):', [0].indexOf(-0));

// SameValueZero is also the key-matching rule of Set/Map: a Set stores and retrieves NaN
console.log('set has NaN:', new Set([NaN]).has(NaN));

// indexOf still fits "give me the position" lookups of normal values; includes only answers presence
console.log('indexOf(1.5):', readings.indexOf(1.5), '| includes(1.5):', readings.includes(1.5));

// fromIndex starts the search at that position: after skipping the head, NaN no longer hits
console.log('includes(NaN, 1):', [NaN, 1].includes(NaN, 1));

// To check "does the data contain a bad value" use includes, not indexOf(NaN) === -1
const dirty = [1, 2, NaN];
console.log('dirty has NaN:', dirty.includes(NaN));
console.log('clean has NaN:', [1, 2, 3].includes(NaN));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

indexOf(NaN): -1
includes(NaN): true
includes(-0 in [0]): true
indexOf(-0 in [0]): 0
set has NaN: true
indexOf(1.5): 0 | includes(1.5): true
includes(NaN, 1): false
dirty has NaN: true
clean has NaN: false

What to watch for

  • indexOf still answers “where”, includes only “whether” — the positional lookup of a normal value works with either.

The same array through both methods:

console.log('indexOf(NaN):', readings.indexOf(NaN));
console.log('includes(NaN):', readings.includes(NaN));

The dirty-data check this example argues for:

const dirty = [1, 2, NaN];
console.log('dirty has NaN:', dirty.includes(NaN));

The printed results make the split visible: for the same array, readings.indexOf(NaN) reports -1 while readings.includes(NaN) reports true. The zero case shows the two methods agreeing — [0].includes(-0) and [0].indexOf(-0) both succeed because ±0 compare equal under every one of these algorithms. new Set([NaN]).has(NaN) returning true is the same rule at work: Set keys match with SameValueZero, so looking up NaN becomes a normal operation. The final checks are the practical payoff — dirty.includes(NaN) flags the bad reading and [1, 2, 3].includes(NaN) clears the clean one, while [NaN, 1].includes(NaN, 1) demonstrates that fromIndex skips the NaN stored at index 0 and reports false.

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free.