How to Determine if a JavaScript Array Contains a Specific Value #javascript #shorts

Posted by

Check if JavaScript array contains a value

Check if JavaScript array contains a value

JavaScript provides an easy way to check if an array contains a specific value. You can use the includes() method to achieve this.

Here’s an example:

      
         
            let fruits = ['apple', 'banana', 'orange', 'grape'];

            if (fruits.includes('banana')) {
               console.log('The array contains banana.');
            } else {
               console.log('The array does not contain banana.');
            }
         
      
   

In this example, we have an array of fruits. We then use the includes() method to check if the array contains the value ‘banana’. If the value is present in the array, the includes() method returns true, otherwise it returns false.

The includes() method can also be used to check if an array contains a value at a specific index. The method takes an optional second parameter which specifies the index at which to start the search. For example:

      
         
            let numbers = [1, 2, 3, 4, 5];

            if (numbers.includes(3, 2)) {
               console.log('The array contains the value 3 starting from index 2.');
            } else {
               console.log('The array does not contain the value 3 starting from index 2.');
            }
         
      
   

So, if you need to check if a JavaScript array contains a specific value, the includes() method is a handy tool to have in your arsenal.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@ModernJavaScript
6 months ago

Want more?? Subscribe for fresh JavaScript tips and tutorials: https://www.youtube.com/@ModernJavaScript?view_as=subscriber?sub_confirmation=1