- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript includes(): Syntax, Usage, and Examples
The includes()
method in JavaScript checks whether a given value exists in a string or array. This functionality is particularly valuable in modern web development when working with data from HTML elements or applying conditional CSS styles. It returns a simple true
or false
depending on whether the value is found.
JavaScript includes () is often used for validation, filtering, and quick membership checks without having to loop through data manually. The method is clean, concise, and extremely useful in both array and string contexts.
Quick Answer: How to Use includes()
in JavaScript
The includes()
method determines whether a string or an array contains a specified value, returning true
or false
as appropriate. It is case-sensitive.
For Arrays: Checks if an array contains a specific element.
const fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape')); // false
For Strings: Checks if a string contains a specific substring.
const sentence = 'Hello, world!';
console.log(sentence.includes('world')); // true
console.log(sentence.includes('World')); // false (because it's case-sensitive)
The includes()
method is the modern, preferred way to check for the presence of a value when you don't need to know its index (position).
How to Use JavaScript includes
The includes()
method has two main use cases—arrays and strings. Here's the general syntax:
For arrays:
array.includes(searchElement, fromIndex)
For strings:
string.includes(searchValue, position)
searchElement
/searchValue
: The item or substring you want to search for.fromIndex
/position
: Optional. Where the search starts. Default is 0.
Both versions return true
if the value is found, otherwise false
. This boolean return value makes it easy to use in conditional statements.
Basic Examples
const colors = ["red", "blue", "green"];
console.log(colors.includes("blue")); // true
const sentence = "JavaScript is awesome";
console.log(sentence.includes("awesome")); // true
When to Use includes JavaScript
JavaScript includes is your go-to method when you want to:
Check If an Array Contains a Value
const fruits = ["apple", "banana", "cherry"];
const hasBanana = fruits.includes("banana");
if (hasBanana) {
console.log("Banana is in the list!");
}
This avoids writing a for
loop or using indexOf()
with comparisons. Unlike traditional iteration methods, includes() provides a more readable syntax.
Test Substrings Within Text
const note = "This message contains important info";
if (note.includes("important")) {
highlightNote(note);
}
Use it to trigger actions based on user input, log messages, or dynamic content.
Perform Validation Logic
const allowedRoles = ["admin", "editor"];
const role = "guest";
if (!allowedRoles.includes(role)) {
console.log("Access denied.");
}
It simplifies permission checks and access control.
Examples of JavaScript includes in Action
With Arrays
const numbers = [10, 20, 30, 40];
console.log(numbers.includes(20)); // true
console.log(numbers.includes(100)); // false
console.log(numbers.includes(30, 3)); // false (starts checking at index 3)
Only the values found at or after the starting index are checked. The method returns false when searching from an index beyond where the value exists.
With Strings
const title = "Mastering JavaScript in 30 Days";
console.log(title.includes("JavaScript")); // true
console.log(title.includes("Python")); // false
console.log(title.includes("Java", 5)); // true
The method respects the order and spacing of characters exactly.
Learn More About the JavaScript includes Method
Case Sensitivity
The method is case-sensitive for both strings and arrays:
const pets = ["Dog", "Cat", "Parrot"];
console.log(pets.includes("dog")); // false
To do a case-insensitive check, normalize both values:
pets.map(p => p.toLowerCase()).includes("dog"); // true
Alternative to indexOf
Before includes()
, developers used indexOf()
:
if (fruits.indexOf("apple") !== -1) {
// Apple is present
}
Today, .includes()
replaces that with cleaner syntax:
if (fruits.includes("apple")) {
// Apple is present
}
Use indexOf()
when you need the exact position; use includes when all you need is a yes or no.
Technical Details and Implementation
The includes()
method is formally defined as array.prototype.includes in the JavaScript specification. This standardized implementation ensures consistency across all JavaScript environments. The method internally checks each element up to the array.length to find a match.
Using .includes JavaScript With Objects and Complex Types
When checking arrays of objects, includes won't work as expected:
const users = [{ name: "Alice" }, { name: "Bob" }];
console.log(users.includes({ name: "Alice" })); // false
Because each object is a different reference in memory, includes can't match them.
Instead, use some()
or find()
:
const hasAlice = users.some(user => user.name === "Alice");
That lets you search based on object values.
Includes in JavaScript Strings with Conditions
You can use includes to build filters:
const comments = [
"Great product!",
"Terrible customer service",
"Product arrived late",
"Fantastic value!"
];
const flagged = comments.filter(comment =>
comment.toLowerCase().includes("terrible")
);
console.log(flagged); // ["Terrible customer service"]
This is useful for moderation tools, keyword highlighting, and search features.
Nested Checks with Multiple Values
To check if a string includes one of several keywords:
const keywords = ["error", "failed", "timeout"];
const logMessage = "Server timeout detected";
const matched = keywords.some(keyword => logMessage.includes(keyword));
console.log(matched); // true
This lets you scale from one check to many, using includes behind the scenes.
Limitations and Quirks
- Doesn’t work on IE (Internet Explorer) without a polyfill.
- Works best for primitive values—objects and arrays are not matched by value.
- You can’t use regular expressions. For pattern-based searches, use
.match()
or.test()
.
JavaScript includes String Validation in Forms
Validate user input cleanly:
const input = "myusername@example.com";
if (!input.includes("@")) {
showError("Email must contain '@'");
}
Simplifies validation without needing regex for every case.
JavaScript Array includes with Numbers and Booleans
You can also check for numbers or booleans in arrays:
const options = [true, false];
console.log(options.includes(true)); // true
const ages = [18, 21, 30];
console.log(ages.includes(21)); // true
As long as the values are primitives, includes works perfectly.
The JavaScript includes method helps you quickly determine if a string contains a substring or if an array contains a value. It’s an essential tool in modern JavaScript—cleaner than index-based methods, easier to read, and ideal for conditions, filters, and validation. Whether you're scanning for keywords, checking roles, or validating form fields, includes in JavaScript keeps your logic concise and expressive.
Key Takeaways for JavaScript includes()
- Returns a Boolean: The primary purpose of
includes()
is to return a simpletrue
orfalse
, making it perfect forif
statements. - Works on Both Strings and Arrays: You can use the same method name for checking for substrings in strings and elements in arrays.
- Case-Sensitive: The search is always case-sensitive.
"Hello".includes("hello")
will befalse
. - Simpler Than
indexOf
: It provides a more readable way to check for presence than the olderindexOf(item) !== -1
pattern. - Doesn't Work for Objects: For arrays of objects,
includes()
will not find a match unless you have the exact same object reference. Usesome()
for these cases instead.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.