lotsoftools

Understanding the Includes Function in JavaScript

Understanding the Includes Function in JavaScript

In JavaScript, the includes function is a helpful method for checking whether a certain value is present within an array or a string. It is available in both Array and String prototypes, with minor differences in their implementation and use. In this article, we will explore the includes function in detail, along with clear examples to help you understand its functionality.

Array.prototype.includes()

The includes() function, when called on an array, checks whether a given value is present in the array or not. It returns a boolean value, true if the value is found and false if not. The syntax for using includes() function on an array is as follows:

array.includes(valueToFind, fromIndex)

JavaScript Array Includes Function Example

Let's see an example of how to use the includes function on an array in JavaScript:

const animals = ['cat', 'dog', 'elephant'];

console.log(animals.includes('cat')); // Output: true
console.log(animals.includes('lion')); // Output: false

String.prototype.includes()

The includes function is also available for strings. When called on a string, it checks whether a given substring is present within the string or not. It returns a boolean value, true if the substring is found and false if not. The syntax for using the includes() function on a string is as follows:

string.includes(searchString, position)

JavaScript String Includes Function Example

Let's see an example of how to use the includes function on a string in JavaScript:

const sentence = 'The quick brown fox jumps over the lazy dog';

console.log(sentence.includes('brown')); // Output: true
console.log(sentence.includes('purple')); // Output: false

Conclusion

In this article, we have discussed the includes function in JavaScript, which is available for both arrays and strings. We have seen examples and provided information on how to use this powerful function to check whether a value is present within a given array or string. With a better understanding of the includes function, you can now effectively utilize this method in your JavaScript projects.