CodeOath
← All posts
JavaScript65 min total · 16 parts

JavaScript Array and Object Methods Cheat Sheet

Contents — Part 4 of 16: Searching and Testing Arrays
Part 4 of 16 · ~1 min

Searching and Testing Arrays

MethodDoesReturns on no matchExample
.find()Returns the first element passing a testundefined[1,2,3].find(x => x > 1)2
.findIndex()Like .find(), but returns the index instead-1[1,2,3].findIndex(x => x > 1)1
.findLast()Like .find(), searching from the endundefined[1,2,3,2].findLast(x => x === 2)2 (the last one)
.indexOf(value)Index of the first exact match (===)-1[1,2,3].indexOf(2)1
.includes(value)true/false for whether a value exists[1,2,3].includes(2)true
.some()true if any element passes a test[1,2,3].some(x => x > 2)true
.every()true if all elements pass a test[1,2,3].every(x => x > 0)true

.includes() vs. .indexOf(): both check for a value's presence, but .includes() correctly finds NaN ([NaN].includes(NaN)true) while .indexOf() cannot ([NaN].indexOf(NaN)-1), because .indexOf() uses strict equality (===) internally and NaN === NaN is famously false. .includes() uses a slightly different algorithm (SameValueZero) specifically to handle this case correctly.

.some() on an empty array always returns false; .every() on an empty array always returns true — both are "vacuously" correct by the mathematical definition, which occasionally surprises people checking an empty list.