Question
How to Check If an Array Contains a Value in JavaScript
Question
How can I check whether a JavaScript array contains a specific value in a concise and efficient way?
For example, I currently use a manual loop like this:
function contains(array, value) {
for (var i = 0; i < array.length; i++) {
if (array[i] === value) {
return true;
}
}
return false;
}
Is there a better built-in JavaScript approach for checking whether an array contains a value?
This question is specifically about checking for a value in an array, rather than finding an object by position.
Short Answer
By the end of this page, you will understand the standard JavaScript ways to check whether an array contains a value. You will learn when to use includes(), how indexOf() compares, what happens with strict equality, and which approach is best for readable modern JavaScript.
Concept
In JavaScript, checking whether an array contains a value is a very common task. You might do this when validating user input, checking permissions, filtering data, or preventing duplicates.
The core idea is simple: given an array, return true if a value exists in it, otherwise return false.
Modern JavaScript provides a built-in method for this:
array.includes(value)
This is usually the clearest and most direct solution.
Before includes() became widely available, developers often used:
array.indexOf(value) !== -1
That works too, but it is less expressive because indexOf() is really designed to return a position, not a boolean.
Why this matters in real programming:
- It improves readability by replacing manual loops with built-in intent-based methods.
- It reduces boilerplate code.
- It makes your code easier to maintain.
- It helps avoid bugs caused by writing the same loop logic repeatedly.
In most beginner-friendly and modern code, includes() is the best choice when you only need to know whether a value exists.
Mental Model
Think of an array like a row of labeled boxes.
If you want to know whether one box contains a certain item, you have two main choices:
includes()asks: “Is this item anywhere in the row?”indexOf()asks: “At what position is this item?”
If all you care about is yes or no, includes() matches your intent better.
Your manual loop is like opening each box one by one yourself. That works, but includes() is like asking a helper who already knows how to do that search for you.
Syntax and Examples
Basic syntax
array.includes(value)
It returns:
trueif the value exists in the arrayfalseif it does not
Example with strings
const fruits = ["apple", "banana", "orange"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false
This is the most readable way to check for a value.
Example with numbers
const luckyNumbers = [3, 7, 10, 42];
console.log(luckyNumbers.includes(10)); // true
.(luckyNumbers.());
Step by Step Execution
Consider this example:
const colors = ["red", "green", "blue"];
const result = colors.includes("green");
console.log(result);
Step by step:
-
colorsis created with three values:- index 0:
"red" - index 1:
"green" - index 2:
"blue"
- index 0:
-
colors.includes("green")starts searching the array. -
JavaScript checks the values one by one:
- Is
"red"equal to"green"? No. - Is
"green"equal to"green"? Yes.
- Is
-
As soon as it finds a match, it returns
true. -
now stores .
Real World Use Cases
Checking whether an array contains a value appears in many real programs.
Form validation
const allowedRoles = ["admin", "editor", "viewer"];
function isValidRole(role) {
return allowedRoles.includes(role);
}
Feature flags
const enabledFeatures = ["dark-mode", "beta-dashboard"];
if (enabledFeatures.includes("dark-mode")) {
console.log("Enable dark mode UI");
}
Preventing duplicates
const tags = ["javascript", "web"];
const newTag = "javascript";
if (!tags.includes(newTag)) {
tags.push(newTag);
}
Access control
const allowedCountries = [, , ];
() {
allowedCountries.(countryCode);
}
Real Codebase Usage
In real codebases, developers usually choose the array-checking method based on what they actually need.
Common pattern: simple membership check
if (selectedIds.includes(id)) {
// already selected
}
This is the most common usage.
Guard clauses
function setTheme(theme) {
const validThemes = ["light", "dark"];
if (!validThemes.includes(theme)) {
throw new Error("Invalid theme");
}
console.log("Theme updated");
}
This pattern rejects invalid values early.
Validation before processing
function createUser(role) {
const allowedRoles = ["admin", "member"];
if (!allowedRoles.includes(role)) {
return { : };
}
{ : };
}
Common Mistakes
1. Using indexOf() incorrectly in a condition
This is a classic bug:
const items = ["a", "b", "c"];
if (items.indexOf("a")) {
console.log("Found");
}
Why it fails:
indexOf("a")returns00is falsy in JavaScript- so the
ifblock does not run
Correct version:
if (items.indexOf("a") !== -1) {
console.log("Found");
}
Or better:
if (items.includes("a")) {
console.();
}
Comparisons
| Approach | Returns | Best when | Example |
|---|---|---|---|
includes() | true or false | You only need to know whether a value exists | arr.includes(3) |
indexOf() | index or -1 | You need the position of the value | arr.indexOf(3) |
some() | true or false | You need custom matching logic, especially for objects | users.some(u => u.id === 1) |
Cheat Sheet
Quick reference
Check if an array contains a value
array.includes(value)
Example
const arr = [1, 2, 3];
arr.includes(2); // true
arr.includes(5); // false
Older alternative
array.indexOf(value) !== -1
Use some() for object properties
const users = [{ id: 1 }, { id: 2 }];
users.some(user => user.id === 2); // true
Key rules
includes()returns a boolean.
FAQ
What is the best way to check if an array contains a value in JavaScript?
Use array.includes(value) in modern JavaScript. It is the clearest way to get a true or false result.
Is includes() better than indexOf()?
For simple existence checks, yes. includes() is more readable because it directly expresses your intent.
Can I use includes() with objects?
Yes, but only for the exact same object reference. If you need to match object properties, use some().
Why does indexOf() sometimes fail in an if statement?
Because if the item is found at index 0, that value is falsy. Always compare with !== -1.
Is includes() case-sensitive?
Yes. For strings in arrays, "Apple" and "apple" are different values.
What should I use for older JavaScript environments?
Mini Project
Description
Build a simple role checker for an application. The program will verify whether a user's role is allowed to access a feature. This demonstrates a real and common use of array membership checks in validation logic.
Goal
Create a function that returns whether a role is allowed, using modern JavaScript array checking.
Requirements
- Create an array of allowed roles.
- Write a function that accepts a role as input.
- Return
trueif the role is allowed andfalseotherwise. - Test the function with at least three different role values.
Keep learning
Related questions
Deep Cloning Objects in JavaScript: Methods, Trade-offs, and Best Practices
Learn how to deep clone objects in JavaScript, compare structuredClone, JSON methods, and recursive approaches with examples.
Get Screen, Page, and Browser Window Size in JavaScript
Learn how to get screen size, viewport size, page size, and scroll position in JavaScript across major browsers with clear examples.
How JavaScript Closures Work: A Beginner-Friendly Guide
Learn how JavaScript closures work with simple explanations, examples, common mistakes, and practical use cases for real code.