JavaScript

How to check if a value exists in an array in JavaScript

You can use the indexOf() method to check whether or not a given value or element exists in an array. The indexOf() method returns the index of the element contained in the array if it is found, otherwise, it returns -1 if it is not found. Consider the following example:
 

How to check if a value exists in an array in JavaScript Using indexOf():
var colors = ["Blue", "Red", "Orange", "Green"];
    
// check if the value exists in the array
if(colors.indexOf("Green") !== -1){
       alert("value exists")
} else{
       alert("value doesn't exists")
}

Output:

value exists
 

How to check if a value exists in an array in JavaScript Using includes():

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

var colors = ["Blue", "Red", "Orange", "Green"];

alert(colors.includes("Blue"));    //true
alert(colors.includes("Yellow"));  //false
alert(colors.includes("Red"));     //true
alert(colors.includes("Gray"));    //false

Output:

true
false
true
false
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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