By the end of this tutorial, you’ll use Lodash’s _.mixin() to attach custom helper functions to Lodash—or to your own objects—safely and predictably.
01
Core Syntax
_.mixin(object, source, options)
02
Extend Lodash
Call _.yourFn() like built-ins.
03
Chain Support
Control chain: true/false.
04
Custom Targets
Mixin into any object.
05
Safe Naming
Prefix helpers; avoid clashes.
06
Isolation
Use runInContext when needed.
Fundamentals
What Is _.mixin()?
_.mixin() copies top-level function properties from a source object onto a destination object. When you omit the first argument, Lodash extends itself—your helpers show up as _.average(), _.vowels(), and similar calls right next to _.map() and _.filter().
💡
Beginner tip — only functions, only top level
_.mixin({ average: fn }) works. _.mixin({ math: { square: fn } }) does not create _.math.square—nested objects are ignored. Group helpers with prefixes like mathSquare instead.
This API shines when you want Lodash-style ergonomics: chainable utilities, a single _ namespace, or plugin-style extensions. In many modern apps, a plain ES module export is simpler—but _.mixin() remains useful for plugins, legacy codebases, and teaching how Lodash itself is extended.
Foundation
📝 Syntax
Merge functions from source onto object (defaults to Lodash):
With chain: true, Lodash wraps mixed-in methods so they plug into fluent pipelines. With chain: false, the mixin returns its raw result from a chain step.
📈 Practical Patterns
Custom targets, naming, and safer alternatives.
Example 3 — Extend your own utility object
You do not have to pollute global Lodash—pass a destination as the first argument.
_.mixin returns the same appUtils reference. This pattern keeps helpers grouped without touching the shared _ singleton.
Example 4 — Prefix names instead of nested namespaces
The old tutorial showed math: { square, cube }—that does not create _.math.square. Use prefixes:
javascript
_.mixin({
mathSquare(n) {
return n * n;
},
mathCube(n) {
return n * n * n;
},
stringCapitalize(str) {
return _.upperFirst(str);
},
});
console.log(_.mathSquare(4));
console.log(_.stringCapitalize("hello"));
// 16
// Hello
📤 Console output:
16
Hello
How It Works
Only top-level functions merge. Prefixes (mathSquare, stringCapitalize) give you readable grouping without fake nested APIs.
🚀 Beyond the Basics
When to use mixin vs modules, and how to stay isolated.
Example 5 — Mixin vs plain module export
Both approaches share logic—the difference is where functions live.
javascript
// Mixin style — attached to _
_.mixin({
statsAverage(array) {
if (!Array.isArray(array) || array.length === 0) return NaN;
return _.sum(array) / array.length;
},
});
// Module style — separate import (often clearer today)
export function average(array) {
if (!Array.isArray(array) || array.length === 0) return NaN;
return array.reduce((a, b) => a + b, 0) / array.length;
}
console.log(_.statsAverage([2, 4, 6]));
// 4 — vs import { average } from './stats'
📤 Console output:
4
When to use which
Prefer modules for app utilities. Reach for _.mixin() when you are building a Lodash plugin, need chain integration, or maintain code that already extends _.
Example 6 — Isolated Lodash with runInContext
Official docs recommend a pristine Lodash copy when mixins should not affect the global _.
runInContext() clones Lodash into a separate function object. Mixins on that copy never appear on the original _—ideal for libraries shipped to many consumers.
Compare
📋 _.mixin vs related patterns
Topic
_.mixin()
ES module export
Object.assign
_.runInContext()
Attaches to
Lodash or any object
Import path
Target object
New _ copy
Chain support
Yes (option)
No
No
Yes on copy
Copies
Functions only
N/A
All own props
N/A (factory)
Global pollution
Possible on _
None
On target
Avoided
Best for
Lodash plugins
Modern apps
Plain objects
Library isolation
🧠 How _.mixin() Works
1
Pick destination
Use the provided object or default to the current Lodash _ instance.
Target
2
Scan source
Iterate own enumerable keys; keep only values where typeof === 'function'.
Filter
3
Attach & wrap
Assign each function to the destination; when chaining is enabled, Lodash wraps it for fluent APIs.
Merge
=
🛠
Extended object
Call new helpers as _.myFn() or dest.myFn()—same reference returned.
Important
📝 Notes
Nested objects in source are not merged—only top-level functions.
Never overwrite built-in Lodash methods like map or filter—use unique, prefixed names.
Document custom mixins so teammates know they are project-specific extensions.
For shared libraries, combine mixin with _.runInContext() instead of mutating global _.
Next in the series: _.noConflict() for restoring the previous _ variable.
Wrap Up
Conclusion
_.mixin() lets you bolt custom utilities onto Lodash—or any object—so helpers feel first-class. Use it thoughtfully: prefix names, respect the chain option, and isolate extensions when you ship code to others.
For many greenfield projects, plain modules are enough. When you need Lodash chains or plugin-style APIs, mixin is the official extension hook.
Use descriptive, prefixed names (mathSquare, appFormatDate)
Extend a dedicated object when you do not need global Lodash pollution
Set chain: false when mixins should return plain values in chains
Use _.runInContext() for library-safe isolated extensions
Document each mixin with JSDoc and a short usage example
❌ Don’t
Expect nested namespaces like _.math.square from nested source objects
Overwrite core Lodash methods (map, get, clone)
Mixin into global _ inside reusable npm packages without isolation
Mix in non-function values—they are silently skipped
Assume Object.assign and mixin behave the same—they copy different things
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about _.mixin()
Use these points when extending Lodash safely.
5
Core concepts
🛠01
Functions only
Top-level merge.
Basics
🔗02
Chain option
Fluent vs plain.
Mechanics
📦03
Any target
Not just _.
Flexible
📝04
Prefix names
Avoid clashes.
Safety
🔒05
runInContext
Isolate mixins.
Libraries
❓ Frequently Asked Questions
_.mixin(object, source, options) copies every own enumerable function property from source onto object. By default object is Lodash itself, so your helpers become callable as _.yourFn() alongside built-ins.
No. Only top-level function properties in source are merged. Nested objects are skipped. Use prefixed names (mathSquare) or extend a dedicated utility object instead.
When chain is true (default), mixed-in functions can participate in Lodash chains: _('fred').vowels().value(). Set { chain: false } when you want the mixin to return a plain value from a chain step without wrapping.
Yes. Pass any destination object as the first argument: _.mixin(myUtils, { hello() { return 'hi'; } }). The function returns the same object for chaining.
For libraries and shared apps, prefer _.runInContext() to get an isolated Lodash copy, then mixin there. Mixing into the global _ can clash with other plugins or overwrite built-ins.
Mixin attaches functions to an existing object (often _) so they feel native and can chain. A module export keeps utilities separate—usually safer and clearer for modern apps. Use mixin when you truly want Lodash-style extensions.
Did you know?
Lodash’s own chaining support for mixed-in methods is why the docs demo vowels with both _.vowels('fred') and _('fred').vowels().value()—the same helper, two calling styles controlled by chain.