Check If an Array Contains a Value in Javascript

Last Updated on April 24, 2024 by Roshan Parihar

To check if array contains value in Javascript, use the includes() function and pass the value as its argument.

You can also use the indexOf() function to find if the value is present in an array in javascript. A loop comparison can also be useful to find the existence of the item in the given array.

Let’s find out with the working examples given.

How to Check If Array Contains Value in Javascript Using includes() Function

If you want to check if an array contains a value using javascript, you can use the includes(). It require an argument to pass the specified value to find if it is present in the given array.

Example 1

Output



The above example contains the declared array with numeric values. The specified value is ’20’ to find whether it is present in the given array or not.

When you click the button given above, it executed the function Countincfn() to start checking if the specified value is present in the array or not. The result is an alert message that shows that the specified value is present in the array.

The function gives the boolean value in the output. If the value is true, it means the value is present. false mean the value is not present.

Using indexOf() Function to Find If Array Contains Value in Javascript

For javascript find if an array contains the specified value, you can also use the indexOf() function and pass the value as its argument. The function finds the index position of the value present in an array. The index position starts from 0 and it’s not negative if the value is present in an array.

Example 2

Output



The above example is a string array with a string as a specified value to find whether it is present in an array or not. When you click the above button, it gives the index position of the value that is greater than or equal to zero (0).

With Loop Comparison to Find Existence

In addition to the above methods, you can also use the loop to compare each value of the array with the specified value to find. It first calculates the length of the array using the array.length method. You have to replace your array variable with array from array.length.

After that, perform a loop and compare each value with the specified value to find using the if condition.

Example 3

Output



When you click the button given above, it performs a comparison with each item of an array. If the value is present in an array, it breaks the loop and displays in an alert that the value is present.

Leave a comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.