Lodash Util methods
What you’ll learn
- What to know before you start (see Prerequisites).
- How the Util group fits together—composition, predicates, stubs, paths, and meta helpers.
- Which helpers return functions (flow, property, constant) versus values (range, toPath, attempt).
- How to import Lodash efficiently in modern bundlers.
- Where to open each
_.methodNametutorial on CodeToFun.
Prerequisites
First-class functions, passing callbacks, and basic object path notation (obj.a.b or obj["a"]). Helpful background from Object methods when examples use _.get with parsed paths.
- Functions as values: storing, passing, and returning functions from other functions.
- Truthy / falsy: predicates in
cond,overEvery, andoverSomerely on standard boolean coercion. - try/catch basics: so
attemptand_.isErrorpatterns make immediate sense. - Modules:
importwith a bundler orrequirein Node.js so the install snippets match your setup.
Key concepts
Lodash Util reuses a small vocabulary across many helpers. These four ideas show up in signatures, docs, and real pipelines.
Composition
flow and flowRight chain unary transforms; only the first step receives multiple outer arguments.
Predicates
matches, conforms, overEvery, and overSome build reusable test functions for filter, find, and cond.
Stub helpers
constant, identity, noop, and stubTrue supply predictable callbacks without inline arrow functions.
Path strings
toPath, property, and method bridge dotted paths and real nested access with _.get.
Overview
Lodash Util is the “glue” category: compose pipelines, harden risky calls, manufacture iteratees, generate ranges and ids, and configure Lodash itself—without reimplementing the same helpers in every project.
Safe & defensive
attempt wraps throws as return values; pair with defaultTo for null-safe fallbacks.
Functional wiring
flow, cond, over, and iteratee keep transforms declarative and reusable.
Generators
range, times, and uniqueId build sequences and labels without manual loops.
⚖️ Lodash Util vs hand-rolled helpers
Many Util patterns are a few lines of vanilla JavaScript. Lodash still helps when you want tested edge cases, consistent iteratee rules, and names your whole team recognizes.
| Situation | Prefer native / manual | Consider Lodash Util |
|---|---|---|
| Two-step transform | x = g(f(x)) | flow(f, g) when the pipeline grows or is reused |
| Safe JSON.parse | try { JSON.parse(s) } catch … | attempt(JSON.parse, s) inside map pipelines |
| Default for null only | x ?? fallback (nullish coalescing) | defaultTo when you need a reusable unary function |
| Numeric sequence | Array.from({ length: n }, (_, i) => i) | range or times with iteratee shorthands |
| Path with brackets | Fragile regex or split hacks | toPath aligned with _.get / _.set |
Install and import
Install the core package once per project, then import individual Util functions so bundlers can tree-shake unused helpers.
npm install lodash import flow from "lodash/flow";
import attempt from "lodash/attempt";
import isError from "lodash/isError";
const parseLines = flow(
(s) => s.trim().split("\n"),
(lines) => lines.map((line) => attempt(JSON.parse, line))
);
const rows = parseLines('{"a":1}\nnot-json\n{"b":2}');
// [ { a: 1 }, SyntaxError, { b: 2 } ]
const ok = rows.filter((r) => !isError(r)); 🔄 Function factories vs immediate values
Some Util APIs return a function you call later; others run immediately and return data. Mixing them up is a common beginner mistake with constant vs stubTrue().
| Style | Typical methods | Rule of thumb |
|---|---|---|
| Returns a function | flow, cond, property, constant, matches, stubTrue (no parens) | Pass to filter, map, or event handlers without wrapping in another arrow. |
| Returns a value now | attempt, range, times, toPath, uniqueId | Call at the point you need the result; store or forward the return value. |
| Stub call form | stubTrue(), stubArray() | With parentheses: immediate constant for one expression. Without: function reference for APIs expecting a callback. |
Suggested learning path
New to Lodash Util? Walk this order in the REPL or a scratch file. Each step builds on the previous one.
- Safe calls:
attemptand_.isErrorfor defensive parsing. - Defaults & stubs:
defaultTo,identity, andstubTruefor predictable callbacks. - Composition:
flow/flowRightfor multi-step transforms. - Branching:
condfor ordered predicate tables. - Paths & ids:
toPathanduniqueIdfor dynamic keys and temp labels.
💻 Environment and versions
- Lodash 4.x: the method index on this page matches stable 4.x Util exports from
lodash@^4on npm. - Node.js and browsers: same package runs in both; use ESM imports in bundlers and Vite, or
require('lodash/flow')in CommonJS projects. - Global `_` scripts:
noConflictmatters when another library also uses_in the browser. - TypeScript: install
@types/lodashfor typings on namespace and per-method imports.
Method index
Each row links to a focused tutorial on this site. URLs follow the /lodash/util/{method-kebab} pattern (for example /lodash/util/flow-right or /lodash/util/unique-id).
| Method | What it does |
|---|---|
_.attempt() | Invoke a function in try/catch; return the result or the caught error object. |
_.bindAll() | Bind own method names on an object so `this` stays fixed when passed as callbacks. |
_.cond() | Build a conditional function from ordered [predicate, handler] pairs (functional if/else chain). |
_.conforms() | Return a predicate that checks whether an object matches a partial shape spec. |
_.constant() | Return a function that always yields the same value (ignores arguments). |
_.defaultTo() | Return a default value only when the input is null or undefined. |
_.flow() | Compose functions left to right; each step receives the previous return value. |
_.flowRight() | Compose functions right to left (mathematical compose / pipeline from the end). |
_.identity() | Return the first argument unchanged—the default iteratee in many Lodash APIs. |
_.iteratee() | Convert property shorthands, matchers, and objects into a callback function. |
_.matches() | Deep partial-match predicate: does the value contain the spec shape? |
_.matchesProperty() | Predicate that checks whether a value at path equals an expected value. |
_.method() | Return a function that invokes a named method on the first argument object. |
_.methodOf() | Like method, but the object is the second argument to the returned function. |
_.mixin() | Add custom functions onto the Lodash prototype (extend Lodash itself). |
_.noConflict() | Restore the previous global `_` variable and return the Lodash instance. |
_.noop() | Empty function that does nothing—placeholder callback or default iteratee. |
_.nthArg() | Return a function that picks the nth argument from the outer call. |
_.over() | Map the same input through multiple functions; return an array of results. |
_.overEvery() | AND-combine predicates: true only when every predicate passes. |
_.overSome() | OR-combine predicates: true when at least one predicate passes. |
_.property() | Return a getter function for a path (shorthand for partial _.get). |
_.propertyOf() | Like property, but the object is passed when the getter is called. |
_.range() | Build a numeric array from start/end/step (end exclusive). |
_.rangeRight() | Like range but produces values from right to left. |
_.runInContext() | Create an isolated Lodash instance with a fresh internal state. |
_.stubArray() | Return a function that always yields a new empty array. |
_.stubFalse() | Return a function that always yields false. |
_.stubObject() | Return a function that always yields a new empty object. |
_.stubString() | Return a function that always yields an empty string. |
_.stubTrue() | Return a function that always yields true (common default branch in _.cond). |
_.times() | Invoke an iteratee n times with indices 0…n−1; collect return values. |
_.toPath() | Convert a dot/bracket path string into an array of key segments. |
_.uniqueId() | Generate an incrementing string id with an optional prefix. |
Pitfalls to avoid
Multi-arg after step one
Only the first composed function receives all outer arguments. Later steps are unary—design pipelines accordingly.
Order matters
Lodash stops at the first truthy predicate. Put specific rules before broad catch-alls; end with stubTrue for a default branch.
Not a UUID
uniqueId is process-scoped and predictable. Use server ids or crypto.randomUUID() for persisted records.
❓ FAQ
Summary
- Scope: Lodash Util covers composition, predicates, stubs, path parsing, sequences, and Lodash meta helpers.
- Bundles: import per method to keep client payloads small.
- Next step: open Lodash _.attempt() or pick any row from the index table above.
Lodash _.flow() composes left to right (first function runs first). _.flowRight() composes right to left—the same direction as mathematical function composition.
9 people found this page helpful
