JavaScript / 4 MIN READ
includes()
Check if arrays contain specific values
From the original Fervor library. Examples may use older package versions.
Using the .includes() Method in JavaScript: Searching and Matching Values
The .includes() method is a built-in function in JavaScript that offers a convenient way to determine whether a specified value is present in an iterable object, such as a string or an array. In this tutorial, we’ll explore how to use the .includes() method to perform searches and match values within various iterable objects.
Introduction to the .includes() Method
The .includes() method is a versatile tool for searching for specific values within iterables. It returns a boolean value true if the specified value is found, and false if it’s not found.
Syntax
The syntax for the .includes() method is as follows:
iterable.includes(valueToFind, startIndex)
iterable: The iterable object, such as a string, array, or another iterable, that will be searched for the specified value.valueToFind: The value to be searched for within the iterable.startIndex(optional): An integer indicating the position in the iterable object where the search should begin. If omitted, the search starts from the beginning.
Using the .includes() Method with Strings
Here’s an example that demonstrates how to use the .includes() method with a string:
const str = "Hello, world!";
const includesWorld = str.includes("world");
console.log(includesWorld); // Output: true
const includesWorldLowercase = str.includes("world", 7);
console.log(includesWorldLowercase); // Output: false
In the first example, the .includes() method checks if the string str includes the value “world”. Since it does, the method returns true.
In the second example, the .includes() method is used with a starting index of 7. This means the search starts from the 7th position in the string. As the substring “world” does not appear after the 7th index, the method returns false.
Bonus Tips and Use Cases
-
Case Sensitivity: The
.includes()method is case-sensitive, meaning it will only match the specified value if the character case matches exactly. For case-insensitive searches, convert both the iterable and the search term to lowercase or uppercase. -
Use with Arrays: You can also use the
.includes()method with arrays to check if an array contains a specific value. This is useful for determining if an array includes a certain item before performing an action on that item. -
Use with Start Index: Utilize the
.includes()method’s optionalstartIndexparameter to start the search from a specific position in the iterable. This can be useful for skipping initial items in an array or characters in a string. -
Avoid Negative Indices: The
.includes()method does not support negative indices. For searching from the end of an array or string, use the.slice()method to extract a portion of the iterable starting from the end. -
Conditionals and Loops: The boolean value returned by the
.includes()method can be directly used in conditional statements likeif,while, orforloops.
Practical Example: Custom Search Function
Here’s a practical example that utilizes the .includes() method to create a search function for matching multiple properties of objects:
const products = [
{ id: 1, name: "iPhone 12", brand: "Apple", price: 799 },
{ id: 2, name: "Galaxy S21", brand: "Samsung", price: 699 },
{ id: 3, name: "Pixel 5", brand: "Google", price: 699 }
];
function searchProducts(query) {
return products.filter(product => {
const { name, brand } = product;
return name.includes(query) || brand.includes(query);
});
}
const results = searchProducts("phone");
console.log(results);
In this example, the searchProducts function takes a query string and filters the products array using the .includes() method. It checks if the name or brand property of each product matches the query. This is useful for searching products based on different criteria such as name or brand.
Creating an Autocomplete Feature
Another creative use of the .includes() method is to create a simple autocomplete feature for a search input field. Here’s an example:
const fruits = ["apple", "banana", "cherry", "grape", "orange", "pear"];
const input = document.querySelector("#search-input");
const resultsContainer = document.querySelector("#search-results");
function searchFruits(query) {
const matchingFruits = fruits.filter(fruit => fruit.includes(query));
return matchingFruits;
}
input.addEventListener("input", event => {
const query = event.target.value.toLowerCase();
const matchingFruits = searchFruits(query);
resultsContainer.innerHTML = "";
matchingFruits.forEach(fruit => {
const li = document.createElement("li");
li.textContent = fruit;
resultsContainer.appendChild(li);
});
});
This example demonstrates how the .includes() method can be used to create an autocomplete feature. As users type in the input field, the script searches for matching fruits using the searchFruits function and displays suggestions in the resultsContainer.
Conclusion
The .includes() method is a versatile tool that simplifies the process of searching and matching values within iterable objects. Whether you’re working with strings or arrays, the .includes() method provides an efficient and elegant way to check for the presence of specific values. By understanding its capabilities and use cases, you can enhance your JavaScript applications with dynamic and interactive features.
By leveraging the .includes() method, you can easily implement search functionalities, autocomplete features, and more in your JavaScript applications. This method is a valuable tool for working with iterable objects and simplifying tasks related to searching and matching values.