JS Built-ins
← Array107 / 226
ArrayArray.prototype.indexOfbeginner

Array.prototype.indexOf() β€” find first index

πŸ“– Usage Example
const arr = [10, 20, 30, 40]
arr.indexOf(30)  // β†’ 2
arr.indexOf(20)  // β†’ 1

Use indexOf() to find the position of the first occurrence of a value in an array.

Array.prototype.indexOf()

Array.prototype.indexOf(value, fromIndex?) returns the index of the first occurrence of value using strict equality (===), or -1 if not found.

Challenge: Implement firstIndexOf(arr, val) that returns arr.indexOf(val).

firstIndexOf([1, 2, 3, 2], 2) // β†’ 1
firstIndexOf([1, 2, 3], 9)    // β†’ -1
πŸ’‘ Hints (2)
  • β€’ `indexOf` uses strict equality (`===`) β€” it cannot find `NaN`.
  • β€’ `indexOf` returns the first occurrence; use `lastIndexOf` for the last one.