What is the difference between includes and indexOf for arrays?
includes returns true or false and can find NaN. indexOf returns the position or -1, uses strict equality and can never find NaN. Use includes for a yes/no check and indexOf when you need the position.
Explain it simply
Asking "is Rohit in the team?" and asking "which jersey position is Rohit?" are different questions. includes answers the first with true or false. indexOf answers the second with a number, and -1 means not found.
The reason includes exists is readability: arr.indexOf(x) !== -1 is awkward. includes also handles NaN correctly because it uses the SameValueZero comparison, while indexOf uses ===, and NaN === NaN is false.
Both compare objects by reference, so [[1]].includes([1]) is false.
Example
const team = ["Rohit", "Virat", "Bumrah"];
console.log(team.includes("Virat")); // Output: true
console.log(team.indexOf("Bumrah")); // Output: 2
console.log(team.indexOf("Dhoni")); // Output: -1
console.log([NaN].indexOf(NaN)); // Output: -1
console.log([NaN].includes(NaN)); // Output: true
console.log([[1]].includes([1])); // Output: falseWhat to say in the interview
"includes returns a boolean and treats NaN as equal to itself. indexOf returns the index or -1 and never finds NaN. Both use reference comparison for objects, so for objects I use some or find with a condition."
Common mistakes
- Writing if (arr.indexOf(x)) and missing that index 0 is falsy while -1 is truthy.