How to use the indexOf() method In Javascript
The indexOf() method returns the index of the first occurrence of a specified value in an array, or -1 if it is not found.
Syntax:
array.indexOf(value);
Example 1: In this example, we have an array of fruits containing three fruits. We use the indexOf() method to check if the banana is in the array, which returns the index 1 (since the banana is the second element in the array). We also check if grapes are in the array, which returns -1 (since grapes are not found in the array).
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('grapes')); // Output: -1
Output
1 -1
Example 2: In this example, the indexOf() method is used to check if “hamster” is in the animal’s array. If the method returns -1, it means “hamster” is not in the array and the code will output “Hamster is not in the array.” If the method returns a value other than -1, it means “hamster” is in the array and the code will output “Hamster is in the array!”.
const animals = ['dog', 'cat', 'bird', 'rabbit'];
// Check if 'hamster' is in the array using indexOf()
if (animals.indexOf('hamster') !== -1) {
console.log('Hamster is in the array!');
} else {
console.log('Hamster is not in the array.');
};
Output
Hamster is not 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