How Lodash stubTrue Works Across Invocations

Lodash’s _.stubTrue is a utility method designed to act as a predictable predicate function that returns true whenever it is called. This article examines the internal design of _.stubTrue, explaining how its underlying implementation ensures identical return values across invocations, how it handles arguments and execution contexts, and why its behavior remains immutable in JavaScript environments.

The Source Implementation

At its core, _.stubTrue is defined with minimal complexity. The source code in Lodash can be represented essentially as:

function stubTrue() {
  return true;
}

Because the function body contains only the literal return statement return true;, it executes no computational logic, reads no external state, and binds no closures to mutable data.

Agnostic to Arguments

JavaScript functions allow any number of arguments to be passed, regardless of the declared parameter list. In the case of _.stubTrue, no parameters are defined, and the internal arguments object is never inspected.

Whether called as _.stubTrue(), _.stubTrue(false), or _.stubTrue(null, 123, {}), the function disregards all passed inputs. Because no inputs affect the execution path, the resulting output remains identical across every invocation.

Agnostic to Execution Context (this)

Functions in JavaScript can have their execution context altered through methods like .call(), .apply(), or .bind(). However, _.stubTrue does not reference the this keyword anywhere in its definition.

Binding _.stubTrue to different contexts or invoking it as a method on different objects has no impact on its return value:

const objA = { method: _.stubTrue };
const objB = { method: _.stubTrue };

objA.method(); // true
objB.method.call(null); // true

Primitive Value and Strict Equality

In JavaScript, true is a primitive boolean value rather than an object. Primitive types are compared by value rather than by reference.

When _.stubTrue executes, it returns the primitive value true. Consequently, any invocation of _.stubTrue() evaluates to strict equality against any other invocation:

_.stubTrue() === _.stubTrue(); // true

Because primitive booleans are immutable and represent a fixed value in the JavaScript memory model, there is no possibility of state divergence between invocations.

Practical Applications

Because of this guaranteed invariance, _.stubTrue is typically employed as: