includes()

🎉
💨
Yes or No? includes() gives us a simple answer!

The includes() Method

The includes() method checks if an array contains a specific item.

It returns true if found, or false if not. Simple as that!

💡
💨

How includes() Works

1const pets = ["cat", "dog", "bird", "fish"];
2
3pets.includes("dog"); // true ✓
4pets.includes("cat"); // true ✓
5pets.includes("lion"); // false ✗
6
7// Great for checking before doing something
8if (pets.includes("dog")) {
9 console.log("You have a dog!");
10}
🤔
💨

includes() vs indexOf()

Both can check if something exists, but they return different things:

1const arr = ["a", "b", "c"];
2
3// indexOf returns a number
4arr.indexOf("b"); // 1
5
6// includes returns true/false
7arr.includes("b"); // true
8
9// includes is cleaner for just checking
10if (arr.includes("b")) { // Easy to read!
11 // do something
12}
🎮

Try It Yourself!

Check if different animals are in our pet array! Get a quick true or false answer.

[
cat
[0]
dog
[1]
bird
[2]
fish
[3]
]
length: 4