Skip to content
jshacks.dev
Fundamentals

JavaScript Array includes Method vs indexOf and NaN

Array includes() tests for a value with SameValueZero, so it finds NaN where indexOf cannot, but it still compares objects by reference. See the pitfalls.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript, Node.js, npm and Vite logos.

The method most code uses to ask "is this value in the list" has been in the language since ES2016, and it still produces two bug reports: it returns false for an object that looks identical to one in the array, and TypeScript refuses to compile a call on a list of literals. Both are consequences of rules that are consistent and easy to forget. This post sets out the comparison includes() uses, how it differs from indexOf(), and the typing problem. Everything runs on Node.js 24, and the wider set of equality rules is in the post on how equality works for objects and arrays.

The basic call is a membership test.

JavaScript
const methods = ["GET", "HEAD", "OPTIONS"];

console.log(methods.includes("GET"));
console.log(methods.includes("POST"));
console.log(methods.includes("get"));
Text
true
false
false

Matching is case sensitive for strings, as with any equality check, so normalize first when the input is not controlled. The result is a boolean, with no index and no -1 to mishandle, which is the main reason to prefer it over indexOf() !== -1 when you only need a yes or no.

The comparison is SameValueZero

includes() does not use ===. It uses an algorithm the spec calls SameValueZero: strict equality, except that NaN equals NaN. Signed zeros are also equal, as with ===.

JavaScript
const readings = [10, NaN, 0];

console.log(readings.includes(NaN));
console.log(readings.indexOf(NaN));
console.log(readings.includes(-0));
Text
true
-1
true

indexOf() uses strict equality, and NaN === NaN is false, so it cannot find NaN. includes() can. Both treat -0 and 0 as equal. If you need to distinguish them, Object.is() is the comparison, and the post on Object.is versus strict equality covers its two differences. For everyday membership tests, includes() behaves the way people assume indexOf() does.

No coercion and reference comparison

There is no type conversion. A number does not match its string form, and two objects match only when they are the same object.

JavaScript
const ids = [1, 2, 3];
console.log(ids.includes("2"));
console.log(ids.includes(Number("2")));

const users = [{ id: 1 }];
console.log(users.includes({ id: 1 }));

const ada = { id: 7 };
console.log([ada].includes(ada));
Text
false
true
false
true

The first mismatch is a standard production bug: an id from a URL is a string, the data holds numbers, and the lookup fails with no error. Convert at the boundary. The second is the object case. A freshly written { id: 1 } is a different object from any stored one, so the test is false even though the contents are equal. For objects, use some() with a comparison on a key, or look up by id in a Map.

Holes and the start index

includes() reads every index and treats a hole as undefined, which differs from indexOf().

JavaScript
const sparse = [, 1];

console.log(sparse.includes(undefined));
console.log(sparse.indexOf(undefined));
Text
true
-1

This difference matters little in practice, since sparse arrays are rare, and it is a good illustration of why the two methods are not interchangeable. The second argument, fromIndex, sets where the search starts, and a negative value counts from the end.

JavaScript
const letters = ["a", "b", "c", "a"];

console.log(letters.includes("a", 1));
console.log(letters.includes("a", -1));
console.log(letters.includes("b", -1));
console.log(letters.includes("a", 10));
Text
true
true
false
false

Starting at index 1 still finds the a at the end. A start of -1 begins at the last item, which is an a, so the first query is true and the b query false. A start beyond the length returns false without looking. A computed start index that overshoots fails quietly, so validate it when it comes from input.

The TypeScript literal problem

When an array is declared as const, its type is a readonly tuple of literal types, and includes() only accepts those literals. A plain string argument is a compile error.

TypeScript
const methods = ["GET", "HEAD"] as const;

function isSafe(method: string): boolean {
  // Error: Argument of type 'string' is not assignable to parameter of type '"GET" | "HEAD"'.
  return methods.includes(method);
}

function isSafeFixed(method: string): boolean {
  return (methods as readonly string[]).includes(method);
}

The compiler is protecting against comparing values that can never match, and here the protection is wrong, because the whole point of the function is to accept an arbitrary string. The cast widens the array to readonly string[] for the call, and it is safe because a wider type only adds possible values. A type guard that narrows method afterwards is a further step: function isSafe(m: string): m is (typeof methods)[number], which returns the same expression and tells callers that a true means one of the literals.

Many lookups need a Set

Each includes() call scans the array until it finds the value or reaches the end. One call on a short list is nothing. Calling it inside a loop over another list multiplies the work.

JavaScript
const blocked = new Set(["spam.test", "junk.test", "ads.test"]);
const senders = ["ada.test", "spam.test", "grace.test"];

const allowed = senders.filter((domain) => !blocked.has(domain));

console.log(allowed);
Text
[ 'ada.test', 'grace.test' ]

Set.prototype.has() does not scan, so its cost does not grow with the number of blocked domains. We switch from includes() to a Set when the list passes a few hundred entries and is queried repeatedly, and we have not found a reason to do it earlier. A Set also uses SameValueZero, so NaN behaves the same. Sets and Maps compared with arrays and objects covers the trade-offs.

Checking several values at once

Two questions come up next: does the list contain any of these values, and does it contain all of them. includes() answers one value, so combine it with some() and every().

JavaScript
const granted = ["read", "write"];
const required = ["read", "delete"];

console.log(required.some((permission) => granted.includes(permission)));
console.log(required.every((permission) => granted.includes(permission)));
Text
true
false

The user holds one of the two required permissions and not both. For small lists this is clear and fast enough. For larger ones, build a Set from granted and use has(). Newer runtimes also give Set the methods isSubsetOf(), intersection() and friends, which express "all of these are present" in one call without the nested loops, and the post on what changed in ES2025 covers them.

An easy mistake here is to write granted.includes(required), passing an array as the value. That compares each item to the array, finds none equal and returns false silently, because no type error is raised in plain JavaScript. If a membership test of a list against a list returns false for data that clearly overlaps, check that you are not testing an array as a single value.

Strings have their own includes

String.prototype.includes() shares the name and tests for a substring, not a member. It throws on a regular expression argument, which is a deliberate guard.

JavaScript
console.log("javascript".includes("script"));

try {
  "javascript".includes(/script/);
} catch (error) {
  console.log(error.name);
}
Text
true
TypeError

Typed arrays also have includes(), with the array semantics. If a value could be a string or an array, check which one you hold before calling it, since a substring test and a membership test return different answers for the same argument.

Normalizing before you compare

Because the comparison is exact, the work moves to the input. Case, whitespace and types should be settled before the call, in one place, and not by loosening the comparison. A small normalizer keeps the list and the query in the same form.

JavaScript
const allowed = ["image/png", "image/jpeg"];

function isAllowedType(header) {
  const type = header.split(";")[0].trim().toLowerCase();
  return allowed.includes(type);
}

console.log(isAllowedType("Image/PNG; charset=binary"));
console.log(isAllowedType("image/gif"));
Text
true
false

The header carried a parameter and different casing, and the function stripped both before the membership test. Putting that cleanup inside the lookup helper means callers cannot forget it.

When includes is the wrong tool

If you need the position, use indexOf(), and mind the -1, as covered in the findIndex() post. If you need to match objects by a property, use some() or find(). If the list is large and queried often, use a Set. If you are testing a condition and not a value, some() says it better.

The method is specified in Array.prototype.includes, and the comparison algorithm is described on MDN's page for equality comparisons and sameness.

Also inTypeScript
Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.