Search arrays with includes() and indexOf()
Quick answer
Includes answers whether a value is present; indexOf reports its first matching index or -1. Their comparison and missing-position behavior differ.
How it works
items.includes(value, fromIndex) uses SameValueZero: NaN matches NaN and signed zeros match. items.indexOf(value, fromIndex) uses strict equality and skips absent indices. Both support a starting index.
const a = ["red", "blue", "red"];console.log(a.includes("blue"), a.indexOf("red"), a.indexOf("green"));Expected output in Node.js:
true 0 -1Membership is Boolean; index zero is a valid match.
const a = [NaN];console.log(a.includes(NaN), a.indexOf(NaN));Expected output in Node.js:
true -1SameValueZero matches NaN while strict equality does not.
Common mistakes
Never test if (items.indexOf(value)) for membership: zero is falsy and -1 is truthy. Use includes or compare explicitly with -1.
Practice
Search for a value at index zero, at a later index and absent from the array.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Search arrays with includes() and indexOf() — Knowledge Check
Apply the taught concept and reason about the result.
What does ["a","b"].indexOf("a") return?
What does [1,2].includes(3) return?
What is [NaN].includes(NaN)?
What is [NaN].indexOf(NaN)?
Why is if(a.indexOf(x)) unreliable for membership?