How to Check if Array includes Value in JavaScript

When you have an array, you might want to check if a specific value is included in the array.
Thankfully, JavaScript has many built-in methods that can help you with this.
In this post, we'll learn how to check if a value is included in an array.
Using the includes method
One way to check if a value is included in an array is to use the includes
method.
This method returns true
if the value is included in the array, and false
if it isn't, which is exactly what we want.
const value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.includes(value);
console.log(included);
true
Using the indexOf method
The indexOf
method will return the index of the value in the array, or -1
if the value was not detected.
This makes it easy to use it to check if the value is included in the array.
const value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.indexOf(value) > -1;
console.log(included);
true
Using the some method
The some
method is an array method that runs a function on each element of the array, and returns true
if the function returns true
for any of the elements.
Here's an example:
const value = "foo";
const array = ["foo", "bar", "baz"];
const included = array.some(element => element === value);
console.log(included);
true
This one is particularly useful when searching for objects:
const array = [{ foo: "baz" }, { foo: "bar" }];
const included = array.some(element => element.foo === "bar");
console.log(included);
true
Using the some
method, we were able to check if an object had a foo
value equal to bar
.
Conclusion
In this post, we looked at three different ways that you can check if an array includes a specific value.
You can use the includes
method, the indexOf
method, or the some
method, depending on your use case.
Hope this was helpful and thanks for reading!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!