/  Technology   /  Check if  a Value Exists in an Array in JavaScript
Check if  a Value Exists in an Array in JavaScript

Check if  a Value Exists in an Array in JavaScript

 

Certain methods exist in  JavaScript to check if a value exists in an array.

One of the most convenient ways to determine whether a value is present in an array or not in JavaScript is to use the indexof() method. The indexof() technique uses the index number phenomenon.

The indexOf() method returns the first index in the array at which a given element can be found, or -1 if it does not exist.

JavaScript Code:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Check if  a Value Exists in an Array</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">
    </head>
    <body>
        <script>
          var army=["Lally", "Sky", "Moon", "Star", "Galaxy"];  
            if(army.indexOf("Galaxy ") !== -1)  
            {  
                   document.write("Yes, the value exists!")  
            }  
            else  
            {  
                document.write("No, the value is absent.")  
            }  
            </script>  
    </body>
</html> 

In the above code we have declared an array with list of elements. WIth the use of indexOf method of javaScript in if else conditioning blocks we are checking whether the particular element exists in the array or not. if it exists a message appears that the value exists else the value does not exist.

Output:

Check if  a Value Exists in an Array in JavaScript

 

Leave a comment