How Lodash stubTrue Works Internally

The _.stubTrue method in Lodash is a utility designed to consistently return the primitive boolean value true. This article provides an overview of how _.stubTrue is constructed internally, how it prevents evaluation side-effects and unwanted type coercion, and why it serves as an optimal, memory-efficient default predicate in functional programming patterns.

Internal Implementation

The source implementation of _.stubTrue is intentionally minimal:

function stubTrue() {
  return true;
}

Because it does not accept arguments, mutate scope, or perform dynamic evaluation, the function contains zero runtime branches. It directly emits the primitive literal true, avoiding the runtime overhead of evaluating truthy or falsy states.

Enforcing Explicit Boolean Returns

In JavaScript, conditional evaluation often relies on type coercion (truthy vs. falsy values), which can introduce subtle bugs when handling edge cases like empty strings, zeroes, or undefined.

_.stubTrue provides a strict, deterministic boundary. By returning the explicit primitive literal true rather than a computed truthy value or a wrapped Boolean object, it ensures that downstream operations receiving its output are strictly interacting with a boolean primitive. It cannot be altered by passing unusual argument types, as arguments passed to it are simply ignored by the runtime.

Memory Optimization and Reference Reusability

When building higher-order logic, developers frequently write anonymous functions such as () => true inline. Instantiating anonymous functions repeatedly inside loops or hot code paths forces the engine to allocate new function instances in memory, increasing garbage collection pressure.

_.stubTrue acts as a static, pre-allocated function reference. By reusing the single _.stubTrue reference across an application, developers prevent redundant closures from being allocated on the heap, ensuring deterministic memory usage.

Practical Role in Lodash Compositions

The utility is most frequently utilized as a fallback or base predicate in complex conditional combinations, such as _.cond:

const customResolver = _.cond([
  [isSpecialCase, handleSpecialCase],
  [_.stubTrue, defaultHandler] // Acts as an explicit 'else' branch
]);

In this pattern, _.stubTrue acts as an explicit "match-all" condition. It guarantees that the default handler runs without requiring additional conditional checks or risking unresolved cases.