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:

  1. undefined (including calling the function with no arguments)
  2. 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; // => true

How Lodash Handles Inputs Internally

Under the hood, _.iteratee delegates to an internal function named baseIteratee. Its resolution order is structured as follows:

  1. Functions: If the argument has a typeof of 'function', Lodash returns it directly.
  2. Nullish Check: If value == null evaluates to true (using loose equality), Lodash returns _.identity. This check exclusively matches null and undefined.
  3. Objects and Arrays: If the argument is an object, Lodash generates property matching callbacks via baseMatches (for objects) or baseMatchesProperty (for key-value arrays).
  4. 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;   // => false

When 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.