Array includes(): readable membership checks (ES2016)
What you’ll learn
Section titled “What you’ll learn”- What
includes()returns and how it compares values (SameValueZero). - How it differs from
indexOf()onNaNand holes, and fromString.prototype.includes(). - How to use it for allow-lists and state rules, and the TypeScript error you get with
as constarrays. - When
some()or aSetis the better choice.
Summary
Section titled “Summary”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.
The problem it solves
Section titled “The problem it solves”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)); // trueconsole.log(editableStatuses.includes('shipped')); // falseHow it works
Section titled “How it works”// Fragment: signaturearray.includes(searchElement, fromIndex = 0) // boolean- It compares each element with SameValueZero: no type coercion,
NaNmatchesNaN, and+0matches-0.MapandSetuse the same rule. fromIndexsets 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 beyondlength, the result isfalsewithout searching.- It does not skip holes: a missing element reads as
undefined, so[1, , 3].includes(undefined)istrue.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 ownincludes().
// SameValueZero: NaN matches NaN, and +0 matches -0.console.log([NaN].includes(NaN), [NaN].indexOf(NaN)); // true -1console.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)); // falseconsole.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 trueFor substring searches, see String includes().
TypeScript
Section titled “TypeScript”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.
Realistic example
Section titled “Realistic example”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')); // trueconsole.log(canTransition('shipped', 'paid')); // falseconsole.log(canTransition('constructor', 'paid')); // falseconsole.log(parseSort(new URL('https://orders.example.test/orders?sort=total').searchParams)); // totalconsole.log(parseSort(new URL('https://orders.example.test/orders?sort=password').searchParams)); // createdAtWith 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.
Common mistakes
Section titled “Common mistakes”- Expecting deep equality.
orders.includes({ id: 'o-1' })is alwaysfalsefor a new object literal. Usesome((o) => o.id === 'o-1'). - Mixing types. IDs parsed from a URL are strings;
[101, 102].includes('101')isfalse. Convert first. - Large lists checked in a loop. Each call is a linear scan. For thousands of lookups against a big list, build a
Setonce and usehas(), which also uses SameValueZero. - Confusing it with the string method.
['express shipping'].includes('express')isfalse; the array version matches whole elements. - Refactoring
indexOf()blindly.includes()findsNaNand treats holes asundefined, so a mechanical replacement can change results for those inputs.
When to use it and when not to
Section titled “When to use it and when not to”| 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 |
Compatibility
Section titled “Compatibility”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.
Interview questions
Section titled “Interview questions”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.
Key takeaways
Section titled “Key takeaways”includes()(ES2016) answers “is this value present?” with a boolean.- It uses SameValueZero: finds
NaN, treats-0and+0as equal, never coerces types, and compares objects by reference. - Holes read as
undefined;fromIndexcan be negative. - Use
some()for conditions, aSetfor many lookups, and a type guard foras constarrays in TypeScript.
Related pages
Section titled “Related pages”- String includes(): substring search on strings.
- Array find() and findIndex(): search by condition.
- Map and Set:
Set.has()for fast repeated membership checks. - Exponentiation operator: the other ES2016 addition.
- JavaScript arrays
Official references
Section titled “Official references”- ECMAScript Language Specification:
Array.prototype.includesandSameValueZero(current draft; first published in ECMAScript 2016) - ECMAScript 2016 Language Specification:
Array.prototype.includes - TC39 proposal: Array.prototype.includes
- MDN: Array.prototype.includes()
- MDN: Equality comparisons and sameness
- TypeScript 6.0.3:
lib.es2016.array.include.d.ts