Lodash _.unary() method
What you’ll learn
- Why
mappasses three arguments and how unary hides extras. - How
_.unary(parseInt)restores sane radix defaults. - How unary compares to
_.ary(fn, 1). - When unary hurts debugging because indexes disappear.
Prerequisites
See _.ary(), _.throttle(), and the Function hub.
- Array.prototype.map: callback signature
(element, index, array). - parseInt radix: second parameter selects numeral base.
Overview
_.unary(func) wraps func so only the first invocation argument reaches the inner implementation—every extra parameter Lodash or native iterators supply is ignored.
Syntax
_.unary(func)- func: function whose arity should collapse to one.
- returns: unary wrapper forwarding only the first argument.
Fix map(parseInt)
Without unary the numeric indices become accidental radix arguments.
import unary from "lodash/unary";
["10", "10", "10"].map(parseInt);
// [10, NaN, 2]
["10", "10", "10"].map(unary(parseInt));
// [10, 10, 10]Ignore accidental iteratee metadata
When helper treats the second parameter as optional formatting, map indexes corrupt output unless unary trims arity.
import unary from "lodash/unary";
function label(word, emoji) {
return emoji ? `${emoji} ${word}` : word;
}
["alert", "done"].map(label);
// ["alert", "1 done"] — index 1 is treated like emoji prefix
["alert", "done"].map(unary(label));
// ["alert", "done"]Pair with lodash iterators
Lodash collection methods pass similar triples—unary keeps predicates focused on values.
import unary from "lodash/unary";
import map from "lodash/map";
const doubled = map(["2", "4", "8"], unary(Number));
doubled;
// [2, 4, 8]📋 _.unary vs _.ary(func, 1) vs arrow wrappers
| Approach | When to use | Note |
|---|---|---|
_.unary | Readable unary adapters | Same effect as ary(fn, 1) |
_.ary(fn, 1) | General arity caps | Use higher n for other limits |
(x) => fn(x) | One-off lambdas | No lodash metadata helpers |
Pitfalls to avoid
Needing position-aware logic
Unary removes index access—reach for explicit lambdas when parity or offsets matter.
this-bound APIs
Do not expect unary to preserve method extraction semantics—bind first when internal code relies on receiver state.
Obscure parses
Sometimes (v) => parseInt(v, 10) documents intent better than unary for newcomers.
❓ FAQ
Summary
- Purpose:
_.unaryshields helpers from iterator extras. - Equivalence: matches
_.ary(func, 1)ergonomically. - Next: Lodash _.wrap(), revisit Lodash _.throttle(), or read official _.unary docs.
Lodash documents _.unary as sugar for _.ary(func, 1)—the wrapper keeps arity predictable when third-party APIs forward extra parameters you never meant to consume.
6 people found this page helpful
