Site Admin
Site Admin Founder of MeaningArticles

JavaScript How to Check If a Value Exists in an Array or Not?

Hello Dev.
you may use the indexOf() method to test whether a given value or element exists in an array or now not. The indexOf() method returns the index of the element within the array if it is discovered, and returns -1 if it not discovered. let's see the following example:

indexOf() method use for check if array includes a value or not.


    var car = ["Hyundai", "Toyota", "KIA", "Mahindra", "Tata Motors"];

    // Check if a value exists in the car array
    if(car.indexOf("Tata Motors") !== -1){
        alert("Value exists!")
    } else{
        alert("Value does not exists!")

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 bellow example:


    var car = ["Hyundai", "Toyota", "KIA", "Mahindra", "Tata Motors"];
    alert(fruits.includes("Tata Motors")); // Outputs: true
    alert(fruits.includes("Maruti Suz")); // Outputs: false
    alert(fruits.includes("Mahindra"));  // Outputs: true
    alert(fruits.includes("Tesla"));    // Outputs: false

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

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.