Javascript includes method checks if a specific value is present in the given input which is case sensitive. It can be used for string and array. It returns true if the value is present else it returns false.
Table of Contents
String includes method syntax
string.includes(searchvalue, startIndex);
string – The original string content
searchvalue – the value which we need to search in the given string.
startIndex – This field is optional. The index from which we need to search for the value.
Return value: Boolean
JavaScript Includes method example without index
In the below example, the output is true since the text javascript is present in the input string
var str = "Welcome to javascript tutorial"; console.log(str.includes("javascript"));
Output: true
JavaScript Includes method with index
Here, the startIndex is 1, hence the output is false since the “Welcome” text starts from 0. If we give negative value as a search index, it considers the entire string for search.
var str = "Welcome to javascript tutorial"; console.log(str.includes("Welcome"),1); console.log(str.includes("Welcome"),-1);
Output: false true
Example: Includes method for case sensitive
The below output returns false since JavaScript String includes method is case sensitive. Input string contains Welcome, but search value is welcome.
var str = "Welcome to javascript tutorial"; console.log(str.includes("welcome"));
Output: false
Array includes method syntax
array.includes(searchvalue, startIndex);
array – the original given array
searchvalue – the element to be searched. This is case sensitive.
startIndex – the position from which we need to search for an element. This field is optional and the index starts at 0.
Return value – Boolean
JavaScript Includes method without index
The JavaScript Array includes method in the below example returns true since the element is present in the array. Since index is not present, includes method searches for the element from the starting of the array.
var names = ["Adam","John","Stephen", "Dave"]; console.log(names.includes("John"));
Output: true
JavaScript Includes method with index
The 1st output is false since the search index is 2, and the element “John” is present at position 1.
The 2nd output is true since the search index is 0 which starts from the beginning of an array.
When we pass the index parameter in the includes method, it searches for the element starting from the index.
var names = ["Adam","John","Stephen", "Dave"]; console.log(names.includes("John",2)); console.log(names.include("Dave",0));
Output: false true
Example: Includes method for case sensitive
Since the includes method is case sensitive, 1st output returns false and 2nd output returns true which matches the array element.
var names = ["Adam","John","Stephen", "Dave"]; console.log(names.includes("adam")); console.log(names.includes("Adam"));
Output: false true
Conclusion
This tutorial gives detailed examples of how to use includes() method for both String and Array.