Skip to content

Lodash - Util

The Utility module in Lodash contains a diverse set of helper functions that don’t fit neatly into other categories like Array, Object, or String. These include identity functions, function composition tools, iteration helpers, predicate creators, and more.

These utilities often serve as building blocks or provide convenient shortcuts for common programming patterns.

Method & SyntaxDescription
identity
_.identity(value)
Returns the first argument it receives. Useful as a default iteratee.
constant
_.constant(value)
Creates a function that returns the same value that is provided. Useful for functions that need to always return a specific constant value.
noop
_.noop()
A function that performs no operation and returns undefined. Useful as a default callback or placeholder.
times
.times(n, [iteratee=.identity])
Invokes the iteratee n times, returning an array of the results of each invocation. The iteratee is invoked with one argument: index.
uniqueId
_.uniqueId([prefix=”])
Generates a unique ID. If prefix is given, the ID is appended to it. Useful for generating temporary DOM IDs or keys.
range
_.range([start=0], end, [step=1])
Creates an array of numbers (positive and/or negative) progressing from start up to, but not including, end. Step determines the increment/decrement.
rangeRight
_.rangeRight([start=0], end, [step=1])
Like _.range, but populates numbers in descending order.
defaultTo
_.defaultTo(value, defaultValue)
Checks value to determine whether a default value should be returned in its place. The default value is returned if value is NaN, null, or undefined. Similar to the native Nullish Coalescing Operator (??), but ?? only triggers for null or undefined.
iteratee
.iteratee([func=.identity])
Creates a function that performs iteratee-style shorthand checks (string, object, array). Used internally by many Lodash methods, but can be used to create reusable predicate functions.
matches
_.matches(source)
Creates a function that performs a partial deep comparison between a given object and source, returning true if the given object has corresponding property values, else false.
matchesProperty
_.matchesProperty(path, srcValue)
Creates a function that performs a comparison between the value at path of a given object and srcValue.
property
_.property(path)
Creates a function that returns the value at path of a given object.
propertyOf
_.propertyOf(object)
The inverse of _.property. Creates a function that returns the value at a given path of object.
flow
_.flow([funcs])
Creates a function that returns the result of invoking the given functions from left to right, where each successive invocation is supplied the return value of the previous.
flowRight
_.flowRight([funcs])
Like _.flow, but invokes functions from right to left (function composition).
cond
_.cond(pairs)
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy. Each pair is [predicate, transform].
over
.over([iteratees=[.identity]])
Creates a function that invokes iteratees with the arguments it receives and returns their results.
overEvery
.overEvery([predicates=[.identity]])
Creates a function that checks if all of the predicates return truthy when invoked with the arguments it receives.
overSome
.overSome([predicates=[.identity]])
Creates a function that checks if any of the predicates return truthy when invoked with the arguments it receives.
mixin
_.mixin([object=lodash], source, [options={}])
Adds source functions to the destination object. If object is the Lodash wrapper, methods are added as chainable utility methods. Advanced usage for extending Lodash.
noConflict
_.noConflict()
Reverts the _ variable to its previous value and returns a reference to the Lodash function. Useful in environments where multiple libraries might claim the _ global.
stubFalse / stubTrue / stubArray / stubObject / stubStringFunctions that return false, true, [], {}, or '' respectively. Useful as default values or in tests.

Example: Function Composition and Predicate Helpers

Section titled “Example: Function Composition and Predicate Helpers”
import _ from 'lodash-es';
const users = [
{ id: 1, name: 'Alice', active: false, age: 30 },
{ id: 2, name: 'Bob', active: true, age: 25 },
{ id: 3, name: 'Charlie', active: true, age: 35 }
];
// Predicate created using shorthand
const isActive = _.matchesProperty('active', true);
const isOver30 = (user) => _.get(user, 'age', 0) > 30;
// Find active users over 30 using _.overEvery
const isActiveAndOver30 = _.overEvery([isActive, isOver30]);
const targetUsers = _.filter(users, isActiveAndOver30);
// targetUsers: [{ id: 3, name: 'Charlie', active: true, age: 35 }]
// Example using _.flow for sequential operations
const getActiveUserNames = _.flow([
(arr) => _.filter(arr, isActive), // Filter active users
(arr) => _.map(arr, 'name'), // Get their names
(arr) => arr.sort() // Sort names alphabetically
]);
const activeNames = getActiveUserNames(users);
// activeNames: ['Bob', 'Charlie']
// Generate 5 unique IDs prefixed with 'item_'
const itemIds = _.times(5, () => _.uniqueId('item_'));
// itemIds: ['item_1', 'item_2', 'item_3', 'item_4', 'item_5'] (IDs might vary)
console.log('Active users over 30:', targetUsers);
console.log('Sorted active user names:', activeNames);
console.log('Generated Item IDs:', itemIds);

Lodash utility methods provide flexible tools for creating predicates, composing functions, generating data, and handling common programming tasks in a concise way.