Array.prototype.indexOfLoading saved progress…

Array.prototype.indexOf

Array.prototype.indexOf returns the position of the first element that strictly equals a value, or -1 if there isn't one. It's the older sibling of includes: where includes gives you a yes/no, indexOf gives you where — and it compares with plain ===, so it can't find NaN.

Implement arrayIndexOf(arr, value, fromIndex). Scan from fromIndex (default 0) to the end, returning the index of the first element === value, or -1. A negative fromIndex counts back from the end.

Signature

function arrayIndexOf(arr, value, fromIndex) {
  // returns the first index i (>= fromIndex) where arr[i] === value,
  // or -1 if none; negative fromIndex counts from the end.
}

Examples

arrayIndexOf(['a', 'b', 'c'], 'b'); // 1
arrayIndexOf([5, 6, 5], 5);         // 0  — the FIRST match
arrayIndexOf([1, 2, 3], 9);         // -1 — not found
arrayIndexOf([5, 6, 5], 5, 1);   // 2  — start at index 1, so skip the first 5
arrayIndexOf([1, NaN], NaN);     // -1 — === can't match NaN (use includes for that)

Notes

  • Strict equality — comparison is ===. indexOf([0], '') is -1; no type coercion.
  • First match — return the earliest index; stop as soon as you find it.
  • fromIndex — defaults to 0; a negative value resolves to arr.length + fromIndex, clamped to 0.
  • NaNindexOf can never find NaN, because NaN === NaN is false. That's the one job includes does and indexOf doesn't.
  • Holes — skipped. A hole in a sparse array is never a match, so indexOf won't return its index.
Loading editor…