JS: Array.prototype.indexOf

By Xah Lee. Date: . Last updated: .
xArray.indexOf(value)
  • Return the index of first element that is value.
  • Return -1 if not found.

🛑 WARNING: It cannot find NaN. To check NaN, use Array.prototype.includes.

console.log([3, 4, "a", 6].indexOf("a"));
// 2
xArray.indexOf(value, startIndex)

Search starts at startIndex, can be negative.

console.log(["a", 4, 5].indexOf("a", 0));
// 0

console.log(["a", 4, 5].indexOf("a", 1));
// -1

// index can be negative
console.log(["a", 4, 5].indexOf("a", -1));
// -1

Edge cases

NaN

// cannot find NaN
console.assert([NaN, NaN].indexOf(NaN) === -1);

undefined and sparse array

// can find undefined that exist as array element
console.assert([3, undefined].indexOf(undefined) === 1);

// sparse array
// cannot find non-existent element
console.assert([3, , 4].indexOf(undefined) === -1);

JavaScript. Array Search