How to use the includes() method In Javascript
The includes() method checks if an array includes a certain value, returning the boolean value true or false accordingly.
Syntax:
array.includes(value);
Example 1: In this example, we have an array of fruits containing three fruits. We use the includes() method to check if the banana is in the array, which returns true. We also check if grapes are in the array, which returns false.
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.includes('banana')); // Output: true
console.log(fruits.includes('grapes')); // Output: false
Output
true false
Example 2: In this example, the if-else statement is used to determine if ‘cat’ is in the array. If ‘cat’ is found in the array, the message “Cat is in the array!” will be printed on the console. If ‘cat’ is not found in the array, the message “Cat is not in the array.” will be printed instead.
const animals = ['dog', 'cat', 'bird', 'rabbit'];
// Check if 'cat' is in the array using includes()
if (animals.includes('cat')) {
console.log('Cat is present in the array!');
} else {
console.log('Cat is not present in the array.');
};
Output
Cat is present in the array!
Best Way to Find an Item in an Array in JavaScript
In JavaScript, an array is a collection of elements that can hold different data types. There are various ways to check if a specific item is present in an array. In this article, we will see the possible techniques to find the item in a given array in JavaScript.
The most commonly used methods to find if an item is in a JavaScript array are:
Table of Content
- Using the includes() method
- Using the indexOf() method
- Using the find() method
- Using Array.some() method
- Using forEach Loop
- Using the filter() method
Contact Us