DEV Community

Cover image for JavaScript Includes() Method: The Top 10 Things You Need to Know
Raja MSR
Raja MSR

Posted on • Originally published at rajamsr.com

JavaScript Includes() Method: 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? JavaScript includes() function that helps you to find out the value you are looking for from an array or string. 

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

In this blog post, we will explore:

  • What is 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 case insensitive manner
  • Use multiple conditions with includes() 
  • 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. It also has an optional parameter fromIndex, which specifies the index from where the search should start. If this parameter is not specified, the search will start from the beginning of the array or string.

array.includes(searchString: string, fromIndex?: number)
Enter fullscreen mode Exit fullscreen mode

The includes() function is a useful method for checking whether a specific value or element exists in an array or string. It is widely supported by modern browsers and can be used in a variety of applications, including web development, data analysis, and more.

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 numbers 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 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 string array:

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

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

Enter fullscreen mode Exit fullscreen mode

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’.

At the same time, the result of the includes() function for the word “apr” is false. Because it will do a strict JavaScript String Equality comparison.  There is no month with “apr” in the input array, so it returns false.

2. JavaScript string includes()

JavaScript includes() Method

JavaScript includes() Method

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

The includes() function is case sensitive, meaning that it distinguishes between JavaScript Uppercase and JavaScript Lowercase letters.

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

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

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

Enter fullscreen mode Exit fullscreen mode

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 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 a 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
Enter fullscreen mode Exit fullscreen mode

In this example, we’re checking if the object ‘book’ contains the string ‘Marijn Haverbeke’. Since we can’t use the includes() function directly on an object, we first convert the values of the object into an array using Object.values(). We then use the includes() function on the resulting array to check if it contains the string ‘Marijn Haverbeke’. The result is true since the object does contain the value ‘Marijn Haverbeke’.

When using the includes() function with an object, it will return true only when the property’s full value matches with the search string, otherwise, return false.

4. Includes() JavaScript function with regular expressions

No, it’s not possible to use regular expressions in the includes() function in JavaScript. 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
Enter fullscreen mode Exit fullscreen mode

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 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
Enter fullscreen mode Exit fullscreen mode

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

6. JavaScript includes() partial match search

The includes() function returns true if the search value exactly matches with array elements. It 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
Enter fullscreen mode Exit fullscreen mode

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() with the includes() method, it will return a matching string. If we use findIndex() with includes(), it will return the index of the partially matching element. 

You can follow any one of the approaches to search 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() function? Well, the main difference 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

Enter fullscreen mode Exit fullscreen mode

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.

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

You might also be wondering, What’s the difference between the includes() and the string contains() method? Well, 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

Enter fullscreen mode Exit fullscreen mode

In this example, we’re using the && and || operators combined with JavaScript includes() method. In ‘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 ‘HTML’ it returns true because we used 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 the array type. 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
Enter fullscreen mode Exit fullscreen mode

How to 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 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.`)
}


Enter fullscreen mode Exit fullscreen mode

In conclusion, the includes() built-in function using this you 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 filter(), find(), or findIndex() methods.

You can use JavaScript indexOf(), contains() methods as an alternative to the includes() method. If you want to safely apply the includes() method, make sure the input type is 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!

Content re-published from www.rajamsr.com

Top comments (3)

Collapse
 
femi_akinyemi profile image
Femi Akinyemi

Thanks for sharing 👍

Collapse
 
vulcanwm profile image
Medea

great article!

Collapse
 
onlinemsr profile image
Raja MSR

Thank you!