Q:

How to Check If a Value Exists in an Array in JavaScript

0

How to Check If a Value Exists in an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the indexOf() Method

You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:

<script>    
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

    // Check if a value exists in the fruits array
    if(fruits.indexOf("Mango") !== -1){
        alert("Value exists!")
    } else{
        alert("Value does not exists!")
    }
</script>

ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number, as you can see here:

<script>    
    var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
    alert(fruits.includes("Banana")); // Outputs: true
    alert(fruits.includes("Coconut")); // Outputs: false
    alert(fruits.includes("Orange")); // Outputs: true
    alert(fruits.includes("Cherry")); // Outputs: false
</script>

All modern browsers supports the includes() method and it is preferred for modern applications.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get Day, Month and Year from a Date Object ... >>
<< How to Remove a Property from a JavaScript Object...