*I may be compensated if you purchase through any affiliate links on this site.*
What does includes() do?
How do I use includes?
The syntax is fairly simple.
The first and required parameter you pass the array method is the value that you want to search for in the array. This value is case sensitive, and it is looking for an EXACT match. Both points are important to remember!
Additionally, you can optionally pass a parameter called fromIndex which indicates from what index position you want the method to start searching. In my experience, I have rarely used fromIndex when using the array method includes().
An Example of Includes() Working It’s Magic
Let’s start with an array that is very relevant to 2020.
const outOfStock = ["toilet paper", "water", "paper towels", "hand sanitizer"];
We want to check the outOfStock array to see if there is anything we need that is out of stock at the moment. We want to know if the outOfStock array include toilet paper? How do we check using the array method includes()?
We have the syntax setup, but if we recall, the array method includes() returns a boolean (true or false). How do we capture that value?
We could log the value in the console, but the best way would be to set the statement to a variable. You can then use the variable as needed. If you are just working on your own, feel free to log the value in the console as shown below to verify your answer.
const toiletPaper = outOfStock.includes("toilet paper"); console.log(toiletPaper) //true
Key Things to Remember About Includes()
I hope that you found this to be helpful and straightforward. Here are a few key takeaways regarding includes to help you as you use it out in the wild:
- The value you’re checking in the array is case sensitive.
- The value you’re checking in the array must be an exact match.
- includes() returns a boolean
- Store the response (true/false) as a variable
Did I miss anything? What else would you include about includes()?