Three Ways to Check for a Value in an Array
Learn to use built-in array methods or your own loop
Sometimes you need to find out if a particular value is present within an array. There are many options to accomplish this. I’ve compiled three options for you to choose from. Each has its own pros and cons; ultimately, it’ll serve you best to know all three and learn when to use each strategy.
The .includes() Method
For a simple yes or no, the .includes() method is a simple yet effective way to determine a value’s presence in an array. After passing the value in question as the sole argument, a Boolean true or false will be returned.let names = ["Jim","Sarah","Tychus"];
if(names.includes("Tychus")) {
console.log("Value found");
}
The .indexOf() Method
If you want to know where the value exists within the array in addition to if the value exists, then the .indexOf() method is a healthy option.let names = ["Jim","Sarah","Tychus"];
if(names.indexOf("Tychus") >= 0) {
console.log("Value found");
}
Notice how for .indexOf(), the expression is checking for >= 0. This is because the method will return -1 if the value is not found. Otherwise, it’ll return the index, which is the position within the iterable.
Writing a Manual Loop
Finally, the third method is to simply loop through the array and find if the value exists.
You may already have done this and are looking for a more efficient way, but you’d be surprised to learn— I was — that a manual loop is comparable in performance to the aforementioned methods.function findValue(haystack,needle) {
for(const item of haystack) {
if(item === needle) {
return true;
}
}
return false;
}let names = ["A","B","C","D","E"];
console.log(findValue(names,"D"));
There are a variety of ways to construct the loop. The above snippet uses the for…of technique, but there are a variety of other ways. The .forEach() array method, while loops, and traditional for loops are just some of your options.