Lodash _.spread() method
What you’ll learn
- How
_.spreadunpacks array-like arguments into discrete parameters. - How the optional
startindex mixes fixed prefixes with spread tails. - Async tuple patterns with
Promise.prototype.then. - Pitfalls when arity, holes, or non-array inputs slip through.
Prerequisites
Read _.rest(), _.partial(), and the Function hub.
- Function.prototype.apply: supplying an arguments array.
- Promises: resolving to structured tuples.
Overview
_.spread(func, [start]) adapts functions expecting discrete parameters so callers can pass array-like bundles—ideal after operations that naturally produce tuples.
Syntax
_.spread(func, [start])- func: callee receiving expanded arguments.
- start: index of the argument to spread (defaults to
0). - returns: wrapped invoker performing the expansion.
Spread a single tuple argument
Default start is 0, so the wrapper expects one array-like holding every positional.
import spread from "lodash/spread";
const describe = spread(function (subject, verb, obj) {
return subject + " " + verb + " " + obj + ".";
});
describe(["Ada", "wrote", "notes"]);
// "Ada wrote notes."Pipe tuples through Promises
.then forwards one resolved value—when that value is an array, spread feeds each slot into your merger.
import spread from "lodash/spread";
const combine = spread(function (width, height) {
return width * height;
});
Promise.resolve([8, 6]).then(combine).then(console.log);
// logs 48Keep a prefix argument before spreading
Set start = 1 so the zeroth argument stays scalar while the next slot expands.
import spread from "lodash/spread";
const greetParts = spread(function (name, sep, word) {
return name + sep + word;
}, 1);
greetParts("Ada", [" says ", "hello"]);
// "Ada says hello"📋 _.spread vs _.rest vs apply
| Tool | Shape change | Typical source |
|---|---|---|
_.spread | Array-like argument → discrete params | Tuples from APIs or Promises |
_.rest | Many invocation args → trailing array | Variadic CLI-style inputs |
Function.apply | Manual one-off expansion | Low-level control without lodash wrappers |
Pitfalls to avoid
Tuple length mismatches
Sparse arrays or shorter tuples yield undefined parameters—validate lengths before spreading user data.
Non-array iterables
Lodash relies on array-like length indexing; arbitrary objects without numeric indices fail silently.
Double spreading
Combining spread with rest without a diagram invites confusion—keep intermediate shapes documented.
❓ FAQ
Summary
- Purpose:
_.spreadunpacks bundled arguments before hittingfunc. - Pairing: tuples + Promises + lodash wrappers compose cleanly.
- Next: Lodash _.throttle(), revisit Lodash _.rest(), or read official _.spread docs.
Under the hood lodash treats the value at the spread index as apply-style input—flattening one array slot into consecutive parameters—so pairing spread with Promise.all tuples feels natural.
6 people found this page helpful
