How to use includes in JavaScript Array, String

by Vincy. Last modified on November 21st, 2021.

Coding in JavaScript is one of the critical skills required in building websites. Though mastering JavaScript is a journey to the center of the earth, continuous learning will help you make it.

We have seen some of the JavaScript functions like find(), forEach() earlier. Now, let’s learn about the function includes() in JavaScript.

Quick example


<script>
inputArray = ['Create', 'Read', 'Update', 'Delete', 'Filter'];
inputArray.includes('Read'); //returns true
inputArray.includes('Read','3'); //returns false
inputArray.includes('Error'); //returns false
inputArray.includes('Delete','-1'); //returns false

inputString = 'How to learn JavaScript?';
inputString.includes('learn'); //returns true
inputString.includes('learn','8'); //returns false
</script>
   

About JavaScript includes

It checks if an array or string includes a given value.

In an array context, it checks the given value is one among the array elements. In the string prototype, the includes() in JavaScript checks if the given value is the substring.

Syntax, parameters and return value


includes(searchElement, [fromIndex]);

It has two parameters, searchElement and fromIndex. The fromIndex is optional and its default value is 0 to start with.

The fromIndex accepts signed numbers. With a negative value, it applies this formula to compute the position to start.

fromIndex = arrayLength + signedFromIndex

It returns boolean true if any match is found or false otherwise.

Note:

  • JavaScript includes() searches array or string with case sensitivity.
  • It can also be called as a generic method.
  • It works in most modern browsers.
  • The negative value is not applicable for the includes() in the String prototype.
  • The Array.prototype.includes() will not search for a sub-array.

include in javascript

Where to use JavaScript includes

The includes in JavaScript can be used for many scenarios. Some of them are listed below.

  1. To form a conditional code block based on the presence of the search element in an array or string.
  2. To highlight the keyword in the search result, if the includes in JavaScript returns true.
  3. To make the select, checkbox, radio options selected if the options found in the haystack.

Visit the linked article to know the other array prototype methods in JavaScript.

Examples for using includes in JavaScript

This article includes 4 examples to see how to use JavaScript includes(). Those are,

  1. To search array if a specified element exists or not.
  2. To use includes with a positive or negative fromIndex parameter.
  3. To use String.prototype.includes.
  4. To invoke includes() as a generic method.

Search array element using Includes in JavaScript

This example contains an array of 4 strings. It defines a custom function checkOption() to form a condition using includes().

This function receives a string and applies array.includes() on it. It returns Boolean true if the passed element is found on the array.

It prepares the output string based on the boolean value returned. It writes the log on the console to see the result of the program.

how-to-use-includes-in-javascript-array.php


<script>
    var optionArray = [ 'Create', 'Read', 'Update', 'Delete' ];
    checkOption('Read');
    checkOption('Filter');
    
    function checkOption(keyword) {
    	var isIncludes = optionArray.includes(keyword);
    	if(!isIncludes) {
    		console.log(keyword + ": not exists");
    	} else {
    		console.log(keyword + ": exists");
    	}
    }
</script>
   

Includes function with optional from-index parameter

It uses the optional fromIndex parameter while calling the includes() in JavaScript.

It supplies either positive or negative values in the second parameter. On getting a negative index, it computes the position from where it should start the search.

As passed -1 the computed position is 5, since arrayLength+negativeIndex = 6+(-1) = 5.

From the 5th position, it searches for ‘Pagination’ and returns true. When it searches for ‘Filter’ then it will return false.

javascript-includes-with-from-index.php


<script>
var optionArray = [ 'Create', 'Read', 'Update', 'Delete', 'Filter', 'Pagination' ];

console.log(optionArray.includes('Update', 2));
console.log(optionArray.includes('Update', 3));
console.log(optionArray.includes('Pagination', -1));
console.log(optionArray.includes('Filter',-1));
</script>
   

JavaScript string includes

It’s for using String.prototype.includes() in Javascript. It assigns a long string to a variable and searches the passed keyword on it.

It also receives fromIndex position. A negative index will create no change. This program uses the fromIndex default value 0 and searches the string end to end.

check-string-includes-substring.php


<script>
var inputString = "How much wood would a woodchuck chuck if a woodchuck could chuck wood?";
var result = inputString.includes("woodchuck");
console.log(result);
</script>
   

Invoke includes in JavaScript on array-like objects

JavaScript allows calling the includes() function as a generic method. In the above examples, the includes() is called with respect to this value representing an array or string context.

This example calls the includes in JavaScript on a functions’ argument list instead of an array.

how-to-call-includes-as-generic.php


<script>
(function() {
  console.log(Array.prototype.includes.call(arguments, 'Read', 1));
  console.log(Array.prototype.includes.call(arguments, 'Read', -1));
})('Create', 'Read', 'Update', 'Delete') 
</script>
   

Similar JavaScript methods like includes

There are more functions in JavaScript as like as the includes(). The below list shows some of those functions.

  • find() – applies condition on an array and returns the first element satisfying the condition.
  • findIndex() – as like as find() but returns index instead of the value.
  • indexOf() – returns index by element value.
  • lastIndexOf() – returns last index of an input element. It makes difference if the there are multiple occurances of the passed element.

Conclusion

We have seen about the includes in JavaScript end to end. The above article contains the basic idea about this function. It covers a beginner’s level introductory section and the usage mechanisms.

The examples will make it clear how to use includes in JavaScript. I hope the scenarios to use and the list of related functions gives relevancy to get the idea.

Download

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top