Mastering the includes() Method in JavaScript
Introduction
The includes() method in JavaScript is a simple yet powerful tool for checking if a value exists in an array or a string. 🧠 It returns a boolean — true if the value is found, and false otherwise.
📌 What is includes()?
includes() determines whether an array or string contains a certain value among its entries. This method is case-sensitive for strings and works with both primitive values and references.
- 🔍 Checks if an element exists in an array or substring exists in a string.
- ✅ Returns true if found, otherwise false.
- 📜 Does not modify the original data.
- ⚡ Optional start index for searching.
💡 Syntax
Basic Syntax
array.includes(searchElement, fromIndex)
string.includes(searchString, position)Parameters:
- searchElement / searchString — Value to search for.
- fromIndex / position — (Optional) Index to start searching from.
🧵 Example: Checking in an Array
Includes in an array
const fruits = ["apple", "banana", "mango"];
console.log(fruits.includes("banana")); // true
console.log(fruits.includes("grape")); // false📦 Example: Checking in a String
Includes in a string
const text = "JavaScript is awesome!";
console.log(text.includes("Script")); // true
console.log(text.includes("script")); // false (case-sensitive)➡️ Example: Using Start Index
Start index in includes
const numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3, 3)); // false (starts search at index 3)⚠️ Important Notes
Note
- Case-sensitive when used with strings.
- For arrays, uses === equality comparison.
- Does not skip NaN — it can detect it correctly (unlike indexOf()).
📊 Quick Reference Table
| Example | Result |
|---|---|
| ["a", "b", "c"].includes("b") | true |
| ["a", "b", "c"].includes("d") | false |
| "hello world".includes("world") | true |
| [NaN].includes(NaN) | true |
>>"includes() answers a simple question: Is it there or not?" 🔍
🔥 Summary
The includes() method is your go-to choice for quick existence checks in arrays and strings. It’s simple, clean, and readable — making your code more intuitive.