Includes() Method in JavaScript (With Examples)


While working with JavaScript, there are various scenarios where developers need to check whether a particular element exists in a string or an array. For this purpose, the “includes()” method is utilized. It provides a simple and easy way to verify whether the given element exists or not. It also eliminates the need for writing complex loops or using other comparison methods to enhance the functionality and readability of the JavaScript code.

This article will demonstrate the JavaScript includes() method.

How to Use the “includes()” Method in JavaScript?

The “includes()” method is utilized for checking/verifying a specific element or substring in an array or a string respectively. It takes an element or a substring as an input and gives a boolean value as output that indicates whether the element or substring is found in the array or string.

Syntax

Follow the provided syntax is used for the includes() methods:

includes(searchElement)

If you want to find the element at a specific index, then, follow the given syntax:

includes(searchElement, fromIndex)

Example

First, we will create an array of numbers:

const numArray = [-5, -2, 11, 3, 8, 15];

Now, here, we will check whether the number “11” exist in the array or not using the “includes()” method:

console.log(numArray.includes(11));

The output shows “true” which means the number “11” is present in the array:

Now, we will pass the “5” as an argument in the “includes()” method to check whether it is present in the array or not:

console.log(numArray.includes(5));

As the output displays “false” that indicates “5” is not exist in the array:

Here, we will identify whether the “-5” exists at the index “1”:

console.log(numArray.includes(-5, 1));

The output indicates that the “-5” does not exist at the index “1”:

Example

In the following example, we will see whether the specified substring exists in the string using the “includes()” methods:

const str = "JavaScript is a scripting language";

Call the includes() method by passing a string as a substring of the “str” and check whether it exists in the string or not:

console.log(str.includes("script"));

Output

That was all about the includes() method in JavaScript.

Conclusion

The “includes()” method is used to check/verify whether a particular element exists in a string or an array. It gives a boolean value as an output that indicates whether the element or substring is found in the array or string. This article demonstrated the JavaScript includes a () method with proper examples.

Print Friendly, PDF & Email
Categories