When Does Lodash iteratee Return identity
In the Lodash utility library, the _.iteratee method
transforms various shorthand values into functional callback predicates.
When provided with specific inputs, _.iteratee defaults to
returning _.identity, a function that simply returns the
first argument it receives without modification. This article breaks
down the precise input types and values that trigger this fallback,
explains the internal mechanism behind it, and clarifies how other falsy
primitives behave differently.
Inputs That Return
_.identity
Lodash's _.iteratee directly returns the
_.identity function when provided with either of the
following primitive nullish values:
undefined(including calling the function with no arguments)null
Additionally, passing the _.identity function
itself will return _.identity, as
_.iteratee returns any supplied function as-is.
Code Demonstration
const _ = require('lodash');
// Calling with undefined or no argument
_.iteratee() === _.identity; // => true
_.iteratee(undefined) === _.identity; // => true
// Calling with null
_.iteratee(null) === _.identity; // => true
// Calling with _.identity directly
_.iteratee(_.identity) === _.identity; // => trueHow Lodash Handles Inputs Internally
Under the hood, _.iteratee delegates to an internal
function named baseIteratee. Its resolution order is
structured as follows:
- Functions: If the argument has a
typeofof'function', Lodash returns it directly. - Nullish Check: If
value == nullevaluates totrue(using loose equality), Lodash returns_.identity. This check exclusively matchesnullandundefined. - Objects and Arrays: If the argument is an object,
Lodash generates property matching callbacks via
baseMatches(for objects) orbaseMatchesProperty(for key-value arrays). - Other Primitives: All remaining types fall through
to
baseProperty, returning a property extractor.
Common Misconception: Falsy Values
Developers often assume that any JavaScript falsy value (such as
false, 0, "", or
NaN) will cause _.iteratee to fall back to
_.identity. This is incorrect.
Because baseIteratee uses the loose equality check
value == null, non-nullish falsy values bypass the identity
return:
// These do NOT return _.identity; they return a property getter (like _.property(0))
_.iteratee(0) === _.identity; // => false
_.iteratee(false) === _.identity; // => false
_.iteratee('') === _.identity; // => false
_.iteratee(NaN) === _.identity; // => falseWhen passed values like 0 or '', Lodash
treats them as property keys and returns a function equivalent to
_.property(value). Therefore, only null,
undefined, and _.identity itself produce the
identity function.