How Lodash _.includes Works on Strings and Arrays

This article explores how the _.includes method in the Lodash library checks for values inside both strings and arrays. It covers the syntax, the underlying SameValueZero equality comparison, how substring matching works, and how the optional index offset parameter behaves during evaluation.

Syntax and Basic Mechanics

The _.includes method checks whether a target value is present inside a given collection. Its signature is:

_.includes(collection, value, [fromIndex=0])

The method accepts a collection (such as an array or a string), the target value to look for, and an optional fromIndex indicating the position to start searching from.

How _.includes Checks Arrays

When evaluated against an array, _.includes iterates through the array elements starting at the index specified by fromIndex (defaulting to 0).

  1. Equality Comparison: Lodash uses the ECMAScript SameValueZero comparison algorithm. This means it behaves almost identically to strict equality (===), with one key exception: it treats NaN as equal to NaN.
    _.includes([1, 2, NaN], NaN); // returns true
  2. Reference Matching: For non-primitive types, such as objects or other arrays, _.includes checks by reference, not by deep structural equality.
    const user = { name: 'Alice' };
    _.includes([user], user); // returns true
    _.includes([{ name: 'Alice' }], { name: 'Alice' }); // returns false
  3. Index Handling: If fromIndex is negative, it is used as an offset from the end of the array. For example, a fromIndex of -2 starts searching from the second-to-last element.

How _.includes Checks Strings

When passed a string as the first argument, _.includes switches behavior from element matching to substring matching.

  1. Substring Matching: Instead of checking for individual characters in an array of characters, it checks whether the provided string exists as a contiguous substring within the source string.
    _.includes('JavaScript', 'Script'); // returns true
    _.includes('JavaScript', 'Java', 1); // returns false (search starts at index 1)
  2. Case Sensitivity: Substring matching is strictly case-sensitive. 'script' will not match 'Script'.
  3. Offset Handling: When fromIndex is provided, any negative index is clamped to 0. Lodash then inspects the string starting from that index toward the end.

Key Differences Between Array and String Handling