Given an array and a value, the task is to check whether an array includes a value in JavaScript. There are various ways to check an array includes a value in JavaScript.
1. Using includes() Method
The includes() method
is the simplest and most readable way to check if an array contains a value. It checks for the existence of a specified value and returns true
if found, otherwise false
.
const arr = [10, 20, 30, 40, 50];
console.log(arr.includes(20)); // Output: true
console.log(arr.includes(25)); // Output: false
2. Using indexOf() Method
The indexOf() method
returns the index of the first occurrence of a specified value in an array. If the value is not found, it returns -1
.
const arr = [10, 20, 30, 40, 50];
console.log(arr.indexOf(30) !== -1); // Output: true
console.log(arr.indexOf(70) !== -1); // Output: false
3. Using find() or findIndex() Methods
The find()
method returns the first element that satisfies a provided testing function, while findIndex()
returns the index of the first matching element. Both can be used to check if a value exists in an array by applying a custom condition.
const arr = [10, 20, 30, 40, 50];
console.log(arr.find(item => item === 70) !== -1);
// Output: true
4: Using a for or forEach Loop
A manual loop allows complete control over the search logic. This is useful for customized searches or for environments that lack modern JavaScript features.
Example with for Loop
const arr = [10, 20, 30, 40, 50];
let found = false;
for (let i = 0; i < arr.length; i++) {
if (arr[i] === 30) {
found = true;
break;
}
}
console.log(found); // Output: true
Example with forEach()
const arr = [10, 20, 30, 40, 50];
let found = false;
arr.forEach(item => {
if (item === 30)
found = true;
});
console.log(found); // Output: true
5: Using some() Method
The some()
method checks if at least one element in an array satisfies a given condition. It returns true
if the condition is met for any element, otherwise false
.
const arr = [10, 20, 30, 40, 50];
console.log(arr.some(item => item === 30)); // Output: true
console.log(arr.some(item => item === 60)); // Output: false
6: Using Set for Faster Lookups
If you frequently check for values in an array, converting it to a Set
can improve performance because Set.has()
is faster for lookups compared to array methods.
const arr = [10, 20, 30, 40, 50];
const numbersSet = new Set(arr);
console.log(numbersSet.has(30)); // Output: true
console.log(numbersSet.has(60)); // Output: false