How to Use Lodash _.constant in JavaScript
Lodash’s _.constant is a higher-order utility function
that generates a new function which always returns a predefined,
immutable value regardless of the arguments passed to it. This article
explains the mechanics of _.constant, explores its
practical use cases in functional programming patterns, and demonstrates
how it improves code readability and maintainability when handling
static callbacks, default states, and testing stubs.
Understanding the Basics
of _.constant
The _.constant function takes a single argument—the
value you want to produce—and returns a function that returns this value
every time it is invoked.
const _ = require('lodash');
const getStatus = _.constant('active');
console.log(getStatus()); // Output: 'active'
console.log(getStatus('ignoredArg', 123)); // Output: 'active'Any arguments provided during subsequent invocations are completely ignored.
Practical Use Cases
1. Cleaner Higher-Order Function Callbacks
In functional programming, methods often require a callback to
generate values. Instead of writing verbose arrow functions like
() => 'default', _.constant offers a
declarative alternative.
// Using an arrow function
const standardArray = Array.from({ length: 3 }, () => 0);
// Using Lodash _.times with _.constant
const lodashArray = _.times(3, _.constant(0));
// Result: [0, 0, 0]2. Strategy Patterns and Conditional Execution
When mapping conditions to behaviors using utilities like
_.cond, every branch must resolve to a function.
_.constant simplifies returning literal values from
conditional logic:
const resolveRolePermissions = _.cond([
[role => role === 'admin', _.constant(['read', 'write', 'delete'])],
[role => role === 'editor', _.constant(['read', 'write'])],
[_.stubTrue, _.constant(['read'])]
]);
console.log(resolveRolePermissions('admin')); // ['read', 'write', 'delete']
console.log(resolveRolePermissions('guest')); // ['read']3. Mocking and Unit Testing
During testing, you frequently need to mock functions to return
specific, static values. _.constant serves as a lightweight
stubbing mechanism:
const mockFetchConfig = _.constant({ timeout: 5000, retries: 3 });
function initializeApp(configProvider) {
const config = configProvider();
return `App initialized with timeout: ${config.timeout}`;
}
console.log(initializeApp(mockFetchConfig));
// Output: App initialized with timeout: 5000Reference Types Consideration
When passing an object, array, or other reference types to
_.constant, the returned function yields a reference to
that original entity rather than a deep clone.
const userTemplate = { role: 'user' };
const getUser = _.constant(userTemplate);
const user1 = getUser();
const user2 = getUser();
user1.role = 'moderator';
console.log(user2.role); // Output: 'moderator'If isolated copies are required, consider pairing
_.constant with _.cloneDeep or instantiating a
factory function instead.
_.constant vs.
ES6 Arrow Functions
While () => value is natively supported in modern
JavaScript, _.constant remains beneficial in environments
relying on point-free style and functional composition. It makes the
developer's intent explicit: the function's output is guaranteed to be
constant, eliminating unintended parameter usage and creating clear,
self-documenting code.