How to Use the includes Method in JavaScript
Checking if an array or string contains a value with includes.
When you only need to know if a value is in an array or a word is in a string,
and not where it is, you can use the includes method.
The includes() method returns true if an array or string contains the
value you pass in, and false if it doesn't.
includes with Arrays
Pass in the value you're looking for:
const fruits = ["apple", "banana", "mango"]fruits.includes("banana") // truefruits.includes("grape") // false
This reads a lot nicer in an if statement than the old way of checking
indexOf:
// The old wayif (fruits.indexOf("banana") !== -1) {// ...}// With includesif (fruits.includes("banana")) {// ...}
includes with Strings
Strings have their own includes method that checks for a piece of text:
const sentence = "The quick brown fox jumps over the lazy dog"sentence.includes("fox") // truesentence.includes("cat") // false
It's case sensitive, so lowercase both sides if you want to match regardless of case:
const search = "FOX"sentence.includes(search) // falsesentence.toLowerCase().includes(search.toLowerCase()) // true
This is the core of a simple search input, paired with filter.
Starting from a Position
Both versions take an optional second argument for where to start looking:
const numbers = [1, 2, 3, 4, 5]numbers.includes(1, 2) // false, starts looking at index 2const word = "javascript"word.includes("java", 1) // false, starts looking at index 1
includes Finds NaN
One small difference from indexOf is how it handles NaN. indexOf can never
find it, but includes can:
const values = [1, NaN, 3]values.indexOf(NaN) // -1values.includes(NaN) // true
You won't run into this often, but it's one more reason to use includes when
you only need a true or false.
Objects Are Compared by Reference
includes checks if the exact same value is in the array. For objects, that
means the same object, not one that looks the same:
const users = [{ name: "Jim" }, { name: "Pam" }]users.includes({ name: "Jim" }) // falseconst jim = users[0]users.includes(jim) // true
To check if an array has an object with a certain property, use some instead:
users.some((user) => user.name === "Jim") // true
And if you need the object itself rather than true or false, use
find.
Checking Against a List of Values
includes is also handy for cleaning up long || conditions. Flip it around
and put the allowed values in an array:
// Instead of thisif (role === "admin" || role === "editor" || role === "owner") {// ...}// Do thisif (["admin", "editor", "owner"].includes(role)) {// ...}
Have some feedback on this post? .