Interview Q&A / JavaScript

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What is the difference between includes and indexOf for arrays?

SHORT ANSWER

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

js
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: false

What 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.

#javascript#arrays

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.