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).
- Equality Comparison: Lodash uses the ECMAScript
SameValueZerocomparison algorithm. This means it behaves almost identically to strict equality (===), with one key exception: it treatsNaNas equal toNaN._.includes([1, 2, NaN], NaN); // returns true - Reference Matching: For non-primitive types, such
as objects or other arrays,
_.includeschecks by reference, not by deep structural equality.const user = { name: 'Alice' }; _.includes([user], user); // returns true _.includes([{ name: 'Alice' }], { name: 'Alice' }); // returns false - Index Handling: If
fromIndexis negative, it is used as an offset from the end of the array. For example, afromIndexof-2starts 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.
- 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) - Case Sensitivity: Substring matching is strictly
case-sensitive.
'script'will not match'Script'. - Offset Handling: When
fromIndexis provided, any negative index is clamped to0. Lodash then inspects the string starting from that index toward the end.
Key Differences Between Array and String Handling
- Type Matching: In arrays, types are preserved
during comparison (e.g.,
'1'does not match1). In strings, non-string target values are coerced to strings before searching. - Negative Indexes: Arrays support negative
fromIndexvalues as backwards offsets from the length of the array, whereas strings clamp negativefromIndexvalues to0.