Skip to content

Array includes(): readable membership checks (ES2016)

  • What includes() returns and how it compares values (SameValueZero).
  • How it differs from indexOf() on NaN and holes, and from String.prototype.includes().
  • How to use it for allow-lists and state rules, and the TypeScript error you get with as const arrays.
  • When some() or a Set is the better choice.

TL;DR: array.includes(value, fromIndex?) returns true if any element equals value, otherwise false. Equality is SameValueZero: like ===, except that NaN equals NaN.

It was added in ECMAScript 2016 (ES7), one of only two features in that edition alongside the exponentiation operator, and it works in every current browser and runtime.

Before ES2016, membership was written as indexOf(x) !== -1 (or >= 0, or ~arr.indexOf(x)). That asks “at what position is this?” when you mean “is this here?”, and indexOf() uses ===, so it can never find NaN.

The proposal was first called contains, but adding that name broke websites using an old version of the MooTools library, so TC39 renamed both the array and string methods to includes in November 2014.

Running the samples: save a sample as a .mjs file and run it with Node.js 22 (node sample.mjs), or paste it into a browser console. The outputs shown were produced with Node.js 22.23.

const editableStatuses = ['draft', 'pending', 'on_hold'];
const status = 'pending';
// Before ES2016: ask for an index, then compare it.
console.log(editableStatuses.indexOf(status) !== -1); // true
// After: say what you mean.
console.log(editableStatuses.includes(status)); // true
console.log(editableStatuses.includes('shipped')); // false
// Fragment: signature
array.includes(searchElement, fromIndex = 0) // boolean
  • It compares each element with SameValueZero: no type coercion, NaN matches NaN, and +0 matches -0. Map and Set use the same rule.
  • fromIndex sets where the search starts. A negative value counts from the end; if the computed start is below 0, the whole array is searched; if it is at or beyond length, the result is false without searching.
  • It does not skip holes: a missing element reads as undefined, so [1, , 3].includes(undefined) is true. indexOf() skips holes.
  • Objects and arrays match by reference, never by contents.
  • It is generic (it works on array-likes through call), and typed arrays have their own includes().
// SameValueZero: NaN matches NaN, and +0 matches -0.
console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // true -1
console.log([-0].includes(0), [0].includes(-0)); // true true
// No type coercion: strings and numbers never match.
console.log([1, 2, 3].includes('2')); // false
// Objects match by reference, not by shape.
const line = { sku: 'SKU-MUG' };
console.log([line].includes(line), [line].includes({ sku: 'SKU-MUG' })); // true false
// Holes are read as undefined (indexOf skips them).
console.log([1, , 3].includes(undefined), [1, , 3].indexOf(undefined)); // true -1
// fromIndex: where to start; negative values count from the end.
const recent = ['a', 'b', 'c', 'd'];
console.log(recent.includes('a', 1)); // false
console.log(recent.includes('c', -2)); // true (starts at index 2)
console.log(recent.includes('a', -10)); // true (clamped to 0)
console.log(recent.includes('d', 4)); // false (start >= length)
// Array includes compares whole elements; String includes searches substrings.
console.log(['express shipping'].includes('express'), 'express shipping'.includes('express')); // false true

For substring searches, see String includes().

The declaration in lib.es2016.array.include.d.ts is includes(searchElement: T, fromIndex?: number): boolean. For a readonly ['pending', 'paid', 'shipped'] tuple created with as const, T is the literal union, so passing an arbitrary string fails to compile. TypeScript 6.0.3 and 7.0.2 both report Argument of type 'string' is not assignable to parameter of type '"pending" | "paid" | "shipped"' (7.0 may order the union differently). Widen the array inside a type guard, which also narrows the input for the caller:

const ORDER_STATUSES = ['pending', 'paid', 'shipped'] as const;
type OrderStatus = (typeof ORDER_STATUSES)[number]; // 'pending' | 'paid' | 'shipped'
// ORDER_STATUSES.includes(input) does not compile when input is a string:
// Argument of type 'string' is not assignable to parameter of type '"pending" | "paid" | "shipped"'.
function isOrderStatus(input: string): input is OrderStatus {
return (ORDER_STATUSES as readonly string[]).includes(input);
}
const raw: string = 'paid';
if (isOrderStatus(raw)) {
const status: OrderStatus = raw; // narrowed
console.log(status);
}
console.log(isOrderStatus('lost'));

Output (compiled with tsc --strict --target es2022, run with Node.js 22): paid, then false. includes() itself does not narrow its argument; the explicit input is OrderStatus predicate does.

OrdersPortal uses includes() for two everyday checks: whether a status change is allowed, and whether a user-supplied sort field is on an allow-list before it reaches a database query.

// order-rules.mjs - OrdersPortal status rules and query validation.
const SORT_FIELDS = ['createdAt', 'total', 'customer'];
// A Map, not a plain object: TRANSITIONS['constructor'] would find an inherited function.
const TRANSITIONS = new Map([
['pending', ['paid', 'cancelled']],
['paid', ['shipped', 'refunded']],
['shipped', ['delivered', 'returned']],
['delivered', ['returned']],
]);
export function canTransition(from, to) {
// Unknown "from" states have no allowed transitions.
return TRANSITIONS.get(from)?.includes(to) ?? false;
}
export function parseSort(searchParams) {
const field = searchParams.get('sort');
// Never pass user input straight into a query: check it against an allow-list.
return SORT_FIELDS.includes(field) ? field : 'createdAt';
}
console.log(canTransition('paid', 'shipped')); // true
console.log(canTransition('shipped', 'paid')); // false
console.log(canTransition('constructor', 'paid')); // false
console.log(parseSort(new URL('https://orders.example.test/orders?sort=total').searchParams)); // total
console.log(parseSort(new URL('https://orders.example.test/orders?sort=password').searchParams)); // createdAt

With a plain object, TRANSITIONS['constructor'] would return the inherited Object function, and ?.includes(to) would throw TypeError: TRANSITIONS[from]?.includes is not a function: optional chaining guards only against null and undefined. A Map (or an object created with Object.create(null)) has no inherited keys.

  • Expecting deep equality. orders.includes({ id: 'o-1' }) is always false for a new object literal. Use some((o) => o.id === 'o-1').
  • Mixing types. IDs parsed from a URL are strings; [101, 102].includes('101') is false. Convert first.
  • Large lists checked in a loop. Each call is a linear scan. For thousands of lookups against a big list, build a Set once and use has(), which also uses SameValueZero.
  • Confusing it with the string method. ['express shipping'].includes('express') is false; the array version matches whole elements.
  • Refactoring indexOf() blindly. includes() finds NaN and treats holes as undefined, so a mechanical replacement can change results for those inputs.
Question Use Equality
Is this exact value in the array? includes() SameValueZero
Where is it? indexOf() / lastIndexOf() === (skips holes, never finds NaN)
Does any element match a condition? some() your predicate
Which element matches? find() your predicate
Many lookups against a large, stable list Set.prototype.has() (Map and Set) SameValueZero
Does a string contain a substring? String.prototype.includes() substring match

According to MDN’s browser compatibility data, Array.prototype.includes() is supported in Chrome 47, Edge 14, Firefox 43, Safari 9, Node.js 6.0, Deno 1.0 and Bun 1.0; the typed-array version needs Safari 10. Internet Explorer never supported it. TypeScript’s types are in lib.es2016.array.include.d.ts. For legacy runtimes, use core-js.

1. What does [NaN].includes(NaN) return, and [NaN].indexOf(NaN)? true and -1. includes() uses SameValueZero, which treats NaN as equal to itself; indexOf() uses strict equality, where NaN !== NaN.

2. Why is the method called includes and not contains or has? contains was not web-compatible: an older MooTools version broke when arrays gained that name. has is used for keys (Map, Set, Reflect), and includes matched the existing String.prototype.includes.

3. Senior scenario: an API gateway checks each request’s tenant ID against an allow-list of 20,000 IDs loaded at startup, using allowed.includes(id). Latency grows with the list. What do you change? Each check is O(n). Build a Set once at startup and call has() for O(1) average lookups with the same equality rules. Normalize the ID type (string versus number) when loading, since neither structure coerces. If the list changes at runtime, swap in a new Set atomically rather than mutating one that requests are reading.

  • includes() (ES2016) answers “is this value present?” with a boolean.
  • It uses SameValueZero: finds NaN, treats -0 and +0 as equal, never coerces types, and compares objects by reference.
  • Holes read as undefined; fromIndex can be negative.
  • Use some() for conditions, a Set for many lookups, and a type guard for as const arrays in TypeScript.