ScanSkill

indexOf

The indexOf() method is used to get the index of an item from an array.

Syntax

array.indexOf(value)

The indexOf() method attaches to the right side of an array with the . operator. It takes in a parameter. It checks if the given parameter exists in the array. If it finds the value, it provides the positional index of the value in the array.

Example

const fruits = ['apple', 'mango', 'banana'];

const indexOfBanana = fruits.indexOf('banana');
console.log(indexOfBanana) // Prints: 2

The indexOf() method returns 2 because arrays are zero-indexed, meaning counting in arrays starts from 0. If we searched the indexOf(’apple’) then the result would be 0.