JavaScript Includes(): The Top 10 Things You Need to Know

Are you searching for a method to find out whether the value exists in a string or an array? The includes() function in JavaScript helps you find out the value you are looking for from an array or string.

The includes() function in JavaScript checks whether a given value or element exists within an array or a string. The includes() method returns a boolean value of true if the specified value is found in the array or string and false otherwise.

In this blog post, we will explore:

  • What is the JavaScript includes() function?
  • JavaScript includes() function with arrays
  • Search within string using includes() function
  • How to use includes() with objects
  • Search using includes() function with regular expression
  • How to use includes() in a case-insensitive manner
  • Use of includes() in JavaScript with multiple conditions 
  • Comparing includes() with contains() and indexOf() methods

Let’s look into each item in detail.

What is includes() in JavaScript?

The includes() function takes in one required parameter, which is the value to be searched for in the array or string.You can also use an optional parameter fromIndex, which specifies the index from which the search should start. If this parameter is not specified, the search will start from the beginning of the array or string.
string.includes(searchString: string, fromIndex?: number)
The includes() function checks whether a specific value or element exists in an array or string.

1. JavaScript includes() function with arrays

Let’s start with arrays. The includes() JavaScript array methods can be used to find out whether or not an array contains a particular element. This method can be used in a string or a number array.

When the includes() function is used with an array to search for an element, it will search for a specific value in the array. The includes() method returns true if it is found and false otherwise. It performs a strict string equality comparison, meaning that the value and the data type of the searched value must match the elements of the array.

Here’s an example of a includes() function with a string array:

const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
console.log(months.includes('Apr'));
// Output: true

console.log(months.includes('apr'));
// Output: false

In this example, we’re checking if the array months contains the string "Apr". The includes() method returns true since the array does contain the value "Apr".

The word "apr" does not exist in the input array. Therefore, the includes() function returns false because it performs a strict JavaScript string equality comparison.

2. JavaScript includes() method

JavaScript includes() Method
JavaScript includes() Method

The includes() function can also be used with strings. The includes() function searches for the presence of the specified string or character in the given string when used with strings. It returns true if the specified string or character is found and false otherwise.

The includes() function distinguishes between JavaScript uppercase and JavaScript lowercase letters because it is case-sensitive.

Here’s an example of the includes() function with a string:

const message = 'Hello, JavaScript!';
console.log(message.includes('JavaScript')); 
// Output: true

console.log(message.includes('javascript')); 
// Output: false

In this example, we’re checking if the string 'message' contains the string 'JavaScript'. The result of the includes() function is true since the string does contain the value 'JavaScript'.

The includes() function returns false for the lowercase search string "javascript". Because it will do case-sensitive searches.

In a later section, we will see how to use the JavaScript includes() function in a case-insensitive() way.

3. Includes() function with objects

The includes() function can even be used with objects. Let’s assume we have an book object with Id, ISBN, title, and price properties. If we want to check the book object by the author’s full name, we can use the includes() function as shown in the following code example:

const book = {
  bookId: 2,
  isbn: "978-1449331818",
  title: "Eloquent JavaScript: A Modern Introduction to Programming",
  author: "Marijn Haverbeke",
  price: 32.99
}

console.log(Object.values(book).includes('Marijn Haverbeke'));
// Output: true

console.log(Object.values(book).includes('Marijn'));
// Output: false

We can use the includes() function with an object to check the book object by the author’s full name. We can convert the object values to an array with the JavaScript Object.values() static method. Then we can use includes() it to see if the array has ‘Marijn Haverbeke’. The result is true because the object has that value.

The includes() function only matches the whole value of a property, not part of it.

JavaScript Object Values
JavaScript Object Values

4. Includes() JavaScript function with regular expressions

It’s not possible to use regular expressions in the includes() function in JavaScript because the includes() function expects a substring as its parameter and performs a simple substring search.

If you want to use regular expressions, you can use the test() method of a regular expression object instead of includes().

const message = 'JavaScript runs everywhere on everything.';
console.log(message.includes(/everywhere/));

// TypeError: First argument to String.prototype.includes must not be a regular expression

5. Includes() function case insensitivity

By default, the includes() function is case-sensitive. However, you can make it case-insensitive by using the toLowerCase() or JavaScript uppercase using the toUpperCase() method on the string you’re searching for. Here’s an example:
const message = 'JavaScript runs everywhere on everything.';
const stringToSearch = 'EVERYWHERE'

console.log(message.toLowerCase().includes(stringToSearch.toLocaleLowerCase())); 
// Output: true

In this example, we convert the entire string to JavaScript lowercase using the toLowerCase() method before using the includes() function to check if the string message variable value includes the string ‘EVERYWHERE’ in a case-insensitive way.

6. JavaScript includes() partial match search

The includes() function will not work on the partial match as expected. To do partial match, you can use includes() along with other JavaScript array methods like filter(), find() or findIndex() as shown in the following example:

let languages = ['C#', 'PHP', 'JavaScript', 'Rust', 'Scala']
let searchTerm = 'Java'

console.log(languages.filter(e => e.includes(searchTerm)))
// Output: ["JavaScript"]

console.log(languages.find(e => e.includes(searchTerm)))
// Output: "JavaScript"

console.log(languages.findIndex(e => e.includes(searchTerm)))
// Output: 2

In the above example, we have a list of programming languages in an array variable 'languages'. We are trying to search "Java" in the list.

  • When the includes() method is used with filter(), it will return partial matching elements as an array.
  • If we use the find() method with the includes() method, it will return a matching string.
  • If we use findIndex() it with includes(), it will return the index of the partially matching element.

You can follow any one of the approaches to searching a string array using partial words.

7. Includes() function vs indexOf()

You might be wondering, What’s the difference between the includes() and the indexOf() functions?

The main difference between includes() and indexOf() is that includes() returns a boolean value indicating whether the value is found, whereas JavaScript indexOf() returns the position of the first occurrence of the value. Returns -1 if it’s not found in the array. Here’s an example:

const programmingLanguages = [
  "JavaScript",
  "Java",
  "C#",
  "TypeScript",
  "F#"
];

const stringToSearch = 'Java'

const hasJava = programmingLanguages.includes(stringToSearch);
console.log(hasJava);
// Output: true

const indexOfJava = programmingLanguages.indexOf(stringToSearch);
console.log(indexOfJava);
// Output: 1
In this example, we’re using both the includes() and indexOf() functions to check if the array variable 'programmingLanguages' contains the string 'Java'.The result of the includes() function is true, which indicates that the array does indeed contain the string 'Java'.The result of the indexOf() function is 1, which is the position of the first occurrence of 'Java' in the array. In JavaScript, the array index starts at 0.
JavaScript indexOf() Array
JavaScript indexOf() Array

8. Includes() function vs. String contains()

You might also be wondering: What’s the difference between the includes() and the string contains() methods?

The contains() method is not actually part of the JavaScript language. It’s a proposed addition to the language, but as of this writing, it’s not yet widely supported. The includes() function, on the other hand, is supported by all major browsers and is part of the ECMAScript 2016 standard.

9. Includes() function with multiple conditions

Finally, you might be wondering, Can I use the includes() function with multiple conditions? The short answer is yes! You can use the logical operators && and || to combine multiple conditions. Here’s an example:

const webTech = ['React', 'C#', 'Angular', 'PHP', 'Vue', 'Node JS'];

const hasReactAndAngular = webTech.includes('React') && webTech.includes('Angular');
console.log(hasReactAndAngular); 
// Output: true

const hasCSharpAndPHP = webTech.includes('C#') || webTech.includes('HTML');
console.log(hasCSharpAndPHP); 
// Output: true

In this example, we’re using the && and || operators combined with the JavaScript includes() method. In the 'webTech' array, we have a list of web frameworks and language names.

On line #3, we are checking whether the webTech array includes both 'React' and 'Angular' using the AND operator (&&). It returns true because webTech array contains both values.

On line #7, we are checking whether the webTech array includes either 'React' or 'HTML' using the OR operator(|| ). Though the input array doesn’t have any'HTML', it returns true because we used the OR condition. When the OR operator is used, it will return true if either one of the conditions is true. In this case, we have 'C#' in the input array.

10. includes() is not a function

You can use the includes() function only on array or string types. It will throw an exception "includes is not a function" error if used on other types. For example, includes() used on Object type and it throws an exception.

const book =   {
    bookId: 1,
    isbn: "978-1491904244",
    title: "JavaScript - The Good Parts",
    author: "Douglas Crockford",
    price: 25.99
  }

  console.log(book.includes())
  // TypeError: book.includes is not a function

How do I avoid this error? Before using the includes() method, ensure that the input type is an array or JavaScript String. This is a simple problem to solve. Use the Array.isArray() function to check whether the input is an array. To identify the type of a string, use the JavaScript typeof keyword.

You can use both of the conditions to make sure the input is an array or string, as shown in the following code:

if (Array.isArray(book) || typeof book === 'string') {
  console.log(book.includes())
}
else {
  console.log(`Input is not type of string or array.`)
}

Conclusion

In conclusion, the includes() built-in function uses this to check if an array, string, or object contains a specific value. With the includes() function, you can’t use a regular expression to search strings.By default, JavaScript includes() method search is case-sensitive; you have to take additional measures to work in a case-insensitive manner.To search using the partial word in a string array, you have to use the includes() method along with the filter(), find(), or findIndex() methods.You can use the JavaScript indexOf() and contains() methods as an alternative to the includes() method. If you want to safely apply the includes() method, make sure the input type is a string or array.By understanding its various use cases and avoiding common mistakes, you can use includes() to write more efficient and effective JavaScript code. So go ahead and give it a try in your own projects!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Scroll to Top