Return correct value from recursive indexOf in JavaScript?

You can create your own function. If the search value is found then the index is returned otherwise return -1.


Following is the code −

const indexOf = (arrayValues, v, index = 0) =>
   index >= arrayValues.length
      ? -1
      : arrayValues[index] === v
         ? index
         : indexOf(arrayValues, v, index + 1)
console.log(indexOf(["John", "David", "Bob"], "Adam"))
console.log(indexOf(["Mike", "Adam", "Carol", "Sam"], "Sam"))

To run the above program, you need to use the below command −

node fileName.js.

Here, my file name is demo321.js.


This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo321.js