How to Check if Array includes Value in JavaScript

Updated onbyAlan Morel
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.

JAVASCRIPT
const value = "foo"; const array = ["foo", "bar", "baz"]; const included = array.includes(value); console.log(included);
BASH
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.

JAVASCRIPT
const value = "foo"; const array = ["foo", "bar", "baz"]; const included = array.indexOf(value) > -1; console.log(included);
BASH
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:

JAVASCRIPT
const value = "foo"; const array = ["foo", "bar", "baz"]; const included = array.some(element => element === value); console.log(included);
BASH
true

This one is particularly useful when searching for objects:

JAVASCRIPT
const array = [{ foo: "baz" }, { foo: "bar" }]; const included = array.some(element => element.foo === "bar"); console.log(included);
BASH
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.