🎉
💨
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"];23pets.includes("dog"); // true ✓4pets.includes("cat"); // true ✓5pets.includes("lion"); // false ✗67// Great for checking before doing something8if (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"];23// indexOf returns a number4arr.indexOf("b"); // 156// includes returns true/false7arr.includes("b"); // true89// includes is cleaner for just checking10if (arr.includes("b")) { // Easy to read!11 // do something12}
🎮
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