jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.includes()

Array.prototype.includes() determines whether an array includes a certain value

Donate to NGO Julenka. Support Ukranians in need. Julenka is an NGO which my brother founded in 2011 to support Ukranian families and kids in need.

Array.prototype.includes() determines whether an array includes a certain value

  • includes() method is defined on the prototype

GIVEN we search simple values

  • WHEN searching an empty list THEN always return false
  • WHEN searching for +0 or -0 THEN they are equal
  • WHEN searching for a small number THEN they are compared by the number`s value
  • WHEN searching for a big number THEN they are compared by the number`s value
  • WHEN searching for true in an array of numbers THEN finds nothing
  • WHEN searching for a boolean in an array with a boolean THEN works as expected

GIVEN we search (more) complex values

  • WHEN searching for NaN THEN it finds it (as opposed to indexOf())
  • WHEN the array has holes THEN they are seen as undefined (not so by indexOf())
  • WHEN searching for an object THEN the same object (not just the same content) must be given
  • WHEN searching for a Symbol THEN only the same symbol is found

types must always match, for example

  • WHEN searching a numeric string THEN types must match
  • WHEN searching a number THEN types must match

the fromIndex parameter, GIVEN we start the search at a certain position in the array

  • WHEN searching from 3rd position THEN find only everything beyond
  • WHEN searching at index beyond the array`s end THEN find nothing

WHEN searching at a negative index

  • THEN use it as index from the end
  • AND it would search before the start (fromIndex < 0) of the array THEN search the entire array

Links

Description of [].includes() on MDN.
The specification describing `Array.prototype.includes()`.
An in-depth article about `includes` quoting the spec.
Announcement of this kata on twitter.
Announcement of this kata on reddit.
Announcement of this kata on hackernews.