How to Check if a Javascript Array Includes a Given Value?
To check if a JavaScript array includes a given value, you can use the includes()
method. Here's an example:
const myArray = [1, 2, 3, 4, 5];
// Check if the array includes the value 3
if (myArray.includes(3)) {
console.log('Value found!');
} else {
console.log('Value not found.');
}
This will output:
Value found!
If the array does not include the given value, the output would be:
Value not found.
You can also use the indexOf()
method to check if an array includes a value, like this:
const myArray = [1, 2, 3, 4, 5];
// Check if the array includes the value 3
if (myArray.indexOf(3) !== -1) {
console.log('Value found!');
} else {
console.log('Value not found.');
}
The indexOf()
method returns the index of the first occurrence of the given value in the array, or -1 if it is not found. In this example, we check if the index returned by indexOf()
is not equal to -1 to determine if the value is in the array.