Loading...
JavaScript

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

You can use the indexOf() method to check if a given 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.

var colors = ["Red", "Blue", "Orange", "Black"];
// Check if an element exist
if(colors.indexOf("Black") !== -1){
   // Black exists 
}else{
   // Black does not exist
}
// Similarly you can try
colors.indexOf("Yellow") !== -1 // false
colors.indexOf("Red") !== -1 // true

You can define a utility function for this purpose and reuse it whenever needed.

function elementExist(arr, element){
  if(arr.indexOf(element) !== -1){
    return true;
  }else{
    return false;
  }
}
// Test the function
var colors = ["Red", "Blue", "Orange", "Black"];
elementExist(colors, "Red") // true
elementExist(colors, "Purple") // false

ES6 has introduced the includes() method to perform this task very easily. This method returns only true or false instead of index number.

var colors = ["Red", "Blue", "Orange", "Black"];
colors.includes("Red") // true
colors.includes("Purple") // false

Please note that includes() method does not work in Internet Explorer (IE) browser.

Try yourself

Share this article with your friends
Leave a Reply

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