JavaScript(JS) JS check if an array contains a specified value
In JavaScript, you can use the includes()
method to check if an array contains a specified value. The includes()
method returns a boolean value indicating whether the specified element is found in the array or not.
Here's an example:
let array = ['apple', 'banana', 'orange']; console.log(array.includes('banana')); // Output: true console.log(array.includes('grape')); // Output: false
In the example above, we define an array array
with three elements. We then use the includes()
method to check if the array contains the value 'banana'
. The method returns true
because 'banana'
is found in the array. We then check if the array contains the value 'grape'
. The method returns false
because 'grape'
is not found in the array.
If you need to check for the presence of a specified value in an array and you need to support older browsers that do not support the includes()
method, you can use the indexOf()
method instead. The indexOf()
method returns the index of the specified element in the array, or -1 if the element is not found. Here's an example:
let array = ['apple', 'banana', 'orange']; console.log(array.indexOf('banana') !== -1); // Output: true console.log(array.indexOf('grape') !== -1); // Output: false
In the example above, we use the indexOf()
method to check if the array contains the value 'banana'
. The method returns the index of 'banana'
in the array, which is 1. We then check if the index is not equal to -1, which indicates that the element was found in the array. We do the same thing for the value 'grape'
, which is not found in the array, so the method returns -1 and the expression evaluates to false
.