JavaScript is a highly flexible programming language used for everything from frontend interactivity to backend logic. Among the many useful features JavaScript offers, the includes() method is a particularly powerful and elegant way to make array checks. Whether you’re validating user input, filtering data, or checking permissions, understanding how to use includes() can significantly improve your code’s readability and performance.
TL;DR
The includes() method in JavaScript allows you to easily check if an array contains a specific element. It’s a clean, readable alternative to older methods like indexOf() or looping through arrays manually. Native to ES6, it’s ideal for most array validations, including simple booleans, complex conditions, and even nested arrays with some workarounds. Explore how it works and when to use it effectively in your JavaScript projects.
What is includes() and Why Use It?
The includes() method is a built-in function for arrays introduced in ECMAScript 2016 (ES7). It helps determine whether an array contains a certain value among its entries and returns a boolean (true or false).
It’s straightforward to use:
const fruits = ["apple", "banana", "mango"];
fruits.includes("banana"); // returns true
fruits.includes("grape"); // returns false
Compared to alternatives like indexOf(), which returns -1 if the item is not found, includes() is more expressive and semantically accurate when you’re looking for a true/false response.
Basic Syntax
Here’s the basic syntax of the includes() method:
array.includes(valueToFind, fromIndex)
valueToFind: The value you want to search for.fromIndex(optional): The position in the array at which to begin the search. Default is 0.
For example:
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.includes(30)); // true
console.log(numbers.includes(25)); // false
console.log(numbers.includes(30, 3)); // false because search begins at index 3
Common Use Cases
The includes() method can be used in many real-world scenarios:
- User Role Checks: Verifying if a user has access.
- Form Validations: Validating that input matches allowed values.
- Filtering Options: Removing or displaying specific data.
- Preferences Matching: Checking if a user’s choice is among preset options.
const userRoles = ["admin", "editor", "subscriber"];
if (userRoles.includes("admin")) {
// Grant administrative privileges
}
Comparison with Similar Approaches
Before includes() was introduced, developers relied more heavily on indexOf() or loops:
// Using indexOf
if (userRoles.indexOf("admin") !== -1) {
// Grant admin access
}
While this works, it’s not immediately clear what the code is checking for, especially for someone new to JavaScript. includes() provides a clearer, more readable alternative.
Using includes() with Arrays of Objects
Things get slightly trickier when you have arrays of objects. The includes() method uses a strict equality check (similar to ===), so it won’t work out-of-the-box with arrays of non-primitive types.
For instance:
const items = [{ id: 1 }, { id: 2 }];
console.log(items.includes({ id: 1 })); // false, because objects are references
To solve this, you can use some() or find() instead:
console.log(items.some(item => item.id === 1)); // true
So while includes() is excellent for checking primitive values like strings, numbers, and booleans, it’s not well-suited for checking objects or arrays of objects unless you manage references carefully.
Case Sensitivity Matters
Remember that includes() is case-sensitive. If you check for "Admin" in an array that contains "admin", it will return false.
const roles = ['admin', 'editor', 'subscriber'];
roles.includes('Admin'); // false
To avoid errors from user input, you might want to normalize the input:
const input = "Admin";
roles.includes(input.toLowerCase()); // true
Edge Cases and Caveats
- NaN: Unlike
indexOf(),includes()correctly detectsNaNin arrays.const arr = [NaN]; arr.includes(NaN); // true - Performance: For very large arrays,
includes()performs linearly, scanning the array until it finds a match or reaches the end. - Readability Gains: In team environments or open-source codebases, the clarity of
includes()is a big win compared to older or more complex alternatives.
Chaining and Complex Logic
You can combine includes() with other array methods for more complex conditions. Let’s say you have a user selecting multiple categories, and you want to validate if any of the selected categories are invalid:
const allowed = ['books', 'toys', 'electronics'];
const selected = ['books', 'vehicles'];
const invalidSelections = selected.filter(category => !allowed.includes(category));
console.log(invalidSelections); // ['vehicles']
This type of check is invaluable in form validations or dynamic UI filtering.
Using with Sets or Maps
While includes() is ideal for Arrays, if you are dealing with extremely large datasets where performance is an issue, consider using a Set. Set provides better time complexity for lookup operations.
const allowedSet = new Set(['books', 'toys', 'electronics']);
allowedSet.has('books'); // true
Despite this, includes() remains more intuitive for quick checks and simple use cases.
Browser Compatibility
Almost all modern browsers support includes(), but if you need to cater to IE11 or older environments, you might want a polyfill or fallback method.
Polyfill Example:
if (!Array.prototype.includes) {
Array.prototype.includes = function(searchElement, fromIndex) {
return this.indexOf(searchElement, fromIndex) !== -1;
};
}
Always test your application in the environments your users are accessing it from to avoid unexpected errors.
Conclusion
The includes() method is a modern, elegant solution for checking if a value exists in an array. It provides a cleaner alternative to older approaches, making your code more readable and easier to maintain. While there are some limitations with object references and case sensitivity, with the right precautions, you can integrate includes() into your JavaScript toolkit to manage validations, filters, and conditionals more efficiently.
So next time you’re working with arrays, think of includes() — your trusty ally in clean and concise JavaScript logic.