CodeBlanks Logo Icon CodeBlanks

Checking with includes

JavaScript course · Beginner · Lesson 62/133

Learn to check whether an element is in the array with includes.

Checking membership with includes

The includes method returns a boolean telling whether an element is in the array.

Example: ["apple", "pear"].includes("apple") returns true. If it cannot find the element, it returns false.

Unlike indexOf, you do not deal with -1; you can write if (arr.includes(x)) directly. It also takes a start index as a second argument.

includes versus indexOf

includes returns true/false directly; indexOf returns an index.

For the question "is this element in the array?", includes is more readable: if (arr.includes(x)) versus if (arr.indexOf(x) !== -1).

Both walk the array front to back. The performance difference is usually negligible; includes is preferred for readability.

Exercise Check whether a tag exists in the tags array

Create an array named tags with at least three tag strings. Use tags.includes to check whether a tag exists and print the result with console.log.

Show example solution
Write the array, then check a tag with tags.includes and print the result with console.log.
Example solution:
const tags = ["js", "css", "html"];
const hasJs = tags.includes("js");
console.log(hasJs);

Test yourself

  1. Check whether cat is among the pets

    const pets = ["cat", "dog", "bird"];
    const hasCat = pets.includes(____);
    console.log(hasCat);
    Show answer
    const pets = ["cat", "dog", "bird"];
    const hasCat = pets.includes("cat");
    console.log(hasCat);
  2. What does this code print?

    const nums = [10, 20, 30];
    console.log(nums.includes(25));
    • true
    • 0
    • -1
    • false
    Show answer

    false — Correct. 25 is not in the array; includes returns false.

  3. Match each method with its return value

    includes
    returns true/false
    indexOf
    returns an index
    includes when not found
    returns false

All lessons in Beginner