JS Built-ins
← Array106 / 226
ArrayArray.prototype.includesintermediate

Array.prototype.includes() β€” finding null

πŸ“– Usage Example
const arr = [1, 2, 3]
// verbose:
arr.indexOf(2) !== -1  // β†’ true
// cleaner:
arr.includes(2)        // β†’ true

Prefer includes() over indexOf() !== -1 when you only need a boolean result.

Array.prototype.includes() β€” vs indexOf

Both includes() and indexOf() can find null. However, includes() returns a clean boolean, while indexOf returns a number that must be checked against -1. Use includes() when you only need to know if a value is present.

Challenge: Implement containsNull(arr) that returns true if the array contains null using arr.includes(null).

containsNull([1, null, 3]) // β†’ true
containsNull([1, 2, 3])    // β†’ false
πŸ’‘ Hints (2)
  • β€’ `null` and `undefined` are distinct values β€” `includes(null)` does not match `undefined`.
  • β€’ `includes()` is preferred over `indexOf(x) !== -1` when you only need a boolean.