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

Array.prototype.indexOf() β€” returns -1 when not found

πŸ“– Usage Example
const arr = [1, 2, 3]
arr.indexOf(99)  // β†’ -1  (not found)

indexOf() returns -1 when the value is not present β€” always check for this sentinel.

Array.prototype.indexOf() β€” -1 sentinel

By convention, -1 means "not found" for all index-returning array methods. Always check the return value before using it as an index.

Challenge: Implement indexOf5(arr) that returns the index of 5 in the array, or -1 if not present.

indexOf5([1, 5, 3])  // β†’ 1
indexOf5([1, 2, 3])  // β†’ -1
πŸ’‘ Hints (2)
  • β€’ Check `=== -1` to determine if the element was not found.
  • β€’ Never use the returned index directly without checking for `-1` first.