Question

How to Check If an Array Contains a Value in JavaScript

javascriptarraysalgorithmtime-complexityjavascript-objects

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.

Take Quiz

Syntax and Examples

Basic syntax

array.includes(value)

It returns:

  • true if the value exists in the array
  • false if 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
console.log(luckyNumbers.includes(5));  // false

Older alternative: indexOf()

const fruits = ["apple", "banana", "orange"];

console.log(fruits.indexOf("banana") !== -1); // true
console.log(fruits.indexOf("grape") !== -1);  // false

This works because indexOf() returns:

  • the index if found
  • -1 if not found

Important note about objects

For objects, JavaScript checks by reference, not by content.

const user1 = { name: "Ava" };
const users = [user1];

console.log(users.includes(user1)); // true
console.log(users.includes({ name: "Ava" })); // false

Even though the second object looks identical, it is a different object in memory.

Step by Step Execution

Consider this example:

const colors = ["red", "green", "blue"];
const result = colors.includes("green");
console.log(result);

Step by step:

  1. colors is created with three values:

    • index 0: "red"
    • index 1: "green"
    • index 2: "blue"
  2. colors.includes("green") starts searching the array.

  3. JavaScript checks the values one by one:

    • Is "red" equal to "green"? No.
    • Is "green" equal to "green"? Yes.
  4. As soon as it finds a match, it returns true.

  5. result now stores true.

  6. console.log(result) prints:

true

If the value were not present:

const result = colors.includes("yellow");
console.log(result); // false

JavaScript would check all items and return false at the end.

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 = ["US", "CA", "UK"];

function canAccess(countryCode) {
  return allowedCountries.includes(countryCode);
}

Filtering input values

const blockedWords = ["spam", "scam"];
const message = "This looks like spam";

const hasBlockedWord = blockedWords.some(word => message.includes(word));
console.log(hasBlockedWord); // true

Here, array membership checking is combined with other useful methods like some().

Take Quiz

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 { error: "Role not allowed" };
  }

  return { success: true };
}

Working with object arrays

When arrays contain objects, developers often use some() instead of includes().

const users = [
  { id: 1, name: "Ava" },
  { id: 2, name: "Leo" }
];

const exists = users.some(user => user.id === 2);
console.log(exists); // true

This is common because includes() only works directly for the same object reference, not matching object properties.

Configuration checks

const supportedLocales = ["en", "fr", "es"];

function loadLocale(locale) {
  if (!supportedLocales.includes(locale)) {
    locale = "en";
  }

  return locale;
}

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") returns 0
  • 0 is falsy in JavaScript
  • so the if block does not run

Correct version:

if (items.indexOf("a") !== -1) {
  console.log("Found");
}

Or better:

if (items.includes("a")) {
  console.log("Found");
}

2. Expecting includes() to compare object contents

Broken expectation:

const users = [{ id: 1 }];

console.log(users.includes({ id: 1 })); // false

Why:

  • These are two different object references.

Use some() instead:

const users = [{ id: 1 }];

console.log(users.some(user => user.id === 1)); // true

3. Confusing strings and arrays

const value = "hello";
console.log(value.includes("e")); // true

This works, but it is string logic, not array logic. The method name is the same, but the data type is different.

4. Case sensitivity issues

const fruits = ["Apple", "Banana"];
console.log(fruits.includes("apple")); // false

JavaScript compares exact values.

Possible fix:

const fruits = ["Apple", "Banana"];
console.log(fruits.map(f => f.toLowerCase()).includes("apple")); // true

5. Writing manual loops when a built-in method is clearer

Your loop is valid, but for simple membership checks it adds extra code.

Prefer:

const found = array.includes(value);

This is easier to read and maintain.

Comparisons

ApproachReturnsBest whenExample
includes()true or falseYou only need to know whether a value existsarr.includes(3)
indexOf()index or -1You need the position of the valuearr.indexOf(3)
some()true or falseYou need custom matching logic, especially for objectsusers.some(u => u.id === 1)
Manual loopanything you programYou need full custom controlfor (...) { ... }

includes() vs indexOf()

const numbers = [10, 20, 30];

numbers.includes(20);      // true
numbers.indexOf(20) !== -1; // true

Use includes() when your question is: “Does this value exist?”

Use indexOf() when your question is: “Where is this value?”

includes() vs some()

const users = [{ id: 1 }, { id: 2 }];

users.includes({ id: 1 }); // false
users.some(user => user.id === 1); // true

Use some() when checking a condition, not exact value identity.

Take Quiz

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.
  • indexOf() returns an index or -1.
  • Objects are compared by reference, not by content.
  • String comparisons are case-sensitive.
  • Use includes() for readability when you only need true/false.

Common pattern

if (!allowedValues.includes(input)) {
  throw new Error("Invalid input");
}

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?

If includes() is not available, use indexOf(value) !== -1.

How do I check whether an object with a certain ID exists in an array?

Use some():

users.some(user => user.id === targetId)
Take Quiz

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 true if the role is allowed and false otherwise.
  • Test the function with at least three different role values.
Take Quiz

Keep learning

Related questions

View more