How Lodash flatMap Handles Boolean Primitives
When using the Lodash _.flatMap method on collections
where the iteratee returns strictly boolean primitives, the method
preserves the boolean values without altering, coercing, or discarding
them. Because _.flatMap maps elements and then flattens the
result by a single depth level, non-array values—such as
true and false—are treated as non-flattenable
elements and are retained directly in the final output array.
The Mechanism Behind
_.flatMap
In the Lodash library, _.flatMap(collection, iteratee)
operates as a composition of _.map followed by a
single-level flatten (_.flatten).
The process unfolds in two distinct steps:
- Mapping: The provided collection is iterated over,
and each item is passed to the iteratee function. If the iteratee
returns a primitive boolean, the intermediate mapped array contains pure
boolean values (for example,
[true, false]). - Flattening: Lodash evaluates each item in the
mapped array using an internal
isFlattenablecheck. This check verifies whether an item is an array or an arguments object.
Primitives, including booleans, numbers, and strings, fail the
isFlattenable test. Consequently, Lodash leaves the
primitive boolean values untouched rather than attempting to iterate
over or spread them.
Practical Examples
Consider an operation where the iteratee evaluates conditions that produce boolean primitives:
const _ = require('lodash');
const numbers = [1, 2, 3, 4];
const result = _.flatMap(numbers, (n) => n % 2 === 0);
console.log(result);
// Output: [false, true, false, true]Even if the input contains a mixture of nested arrays containing booleans and raw boolean primitives, only the array wrappers are dissolved:
const mixed = [[true], false, [false, true]];
const result = _.flatMap(mixed, (item) => item);
console.log(result);
// Output: [true, false, false, true]In this scenario:
[true]is an array, so it is unwrapped totrue.falseis a boolean primitive; it fails the flatten check and is pushed directly into the resulting array.[false, true]is an array, so both elements are extracted into the result.
Key Takeaways
- No Type Coercion: Boolean primitives are not cast
to numbers (
0or1), strings, or objects. - No Runtime Exceptions: Passing or returning boolean
values in
_.flatMapdoes not throw an error or trigger anis not iterableexception. - Identity Preservation: Primitives are treated as terminal leaf nodes in Lodash's flattening algorithm, meaning they simply pass through to the resulting array in their original state.