Lodash _.mixin() Method

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
Util utilities

What You’ll Learn

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.

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.

📝 Syntax

Merge functions from source onto object (defaults to Lodash):

javascript
_.mixin([object = lodash], source, [options = {}])

Syntax Rules

  • object — destination to receive new methods (Lodash by default).
  • source — plain object whose own enumerable function properties are copied.
  • options.chain — when true (default), mixed-in fns support Lodash chaining.
  • Return value — the destination object (same reference).
  • Non-functions skipped — strings, numbers, and nested objects in source are not merged.
javascript
import _ from "lodash";



_.mixin({

  average(array) {

    if (!Array.isArray(array) || array.length === 0) return NaN;

    return _.sum(array) / array.length;

  },

});



_.average([5, 10, 15, 20]);

// 12.5

⚡ Quick Reference

TaskCode patternNotes
Extend Lodash_.mixin({ myFn: fn })Default target is _
Extend custom object_.mixin(utils, { fn })First arg = destination
Disable chaining_.mixin(src, { chain: false })Plain return in chains
Chainable call_('fred').vowels().value()chain: true (default)
Namespace helpersmathSquare, mathCubeNo nested _.math.*
Isolated copy_.runInContext().mixin(...)Avoid global pollution
Returns
Object

Destination object

Copies
Functions

Top-level only

Option
chain

Chainable mixins

Category
Util

Extension

🧰 Parameters

Arguments accepted by _.mixin():

object Optional

Destination object or Lodash function. Defaults to the current _ instance.

_.mixin(myUtils, source)
source Required

Object containing functions to attach. Each own enumerable function property is merged onto object.

_.mixin({ average: fn })
options Optional

Configuration object. Most tutorials focus on chain.

{ chain: true }
options.chain Boolean

When true, mixed-in methods work in _('x').myFn() chains. When false, chain steps unwrap to plain values.

_.mixin(src, { chain: false })

If object is a function (Lodash), methods are also added to its prototype so chaining works. See the official docs for edge cases.

Examples Gallery

Practical _.mixin() patterns with copy-ready code, sample output, and interactive Try It Yourself labs.

📚 Getting Started

Add a helper to Lodash and control chaining behavior.

Example 1 — Add average to Lodash

Extend Lodash with a small stats helper callable as _.average().

javascript
_.mixin({

  average(array) {

    if (!Array.isArray(array) || array.length === 0) return NaN;

    return _.sum(array) / array.length;

  },

});



const numbers = [5, 10, 15, 20];



console.log(_.average(numbers));

// 12.5
Try It Yourself

How It Works

Lodash reads each function on source and assigns it to _. After mixin, _.average behaves like any other Lodash utility.

Example 2 — Chainable vs non-chainable mixins

The official vowels example shows how chain affects Lodash sequences.

javascript
function vowels(string) {

  return _.filter(string, (v) => /[aeiou]/i.test(v));

}



_.mixin({ vowels });



console.log(_.vowels("fred"));

// ["e"]



console.log(_("fred").vowels().value());

// ["e"] — chainable (default)



_.mixin({ vowels }, { chain: false });



console.log(_("fred").vowels());

// ["e"] — returns array directly, no .value()
Try It Yourself

How It Works

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.

javascript
const appUtils = {};



_.mixin(appUtils, {

  greet(name) {

    return "Hello, " + name + "!";

  },

  slugify(text) {

    return _.kebabCase(text);

  },

});



console.log(appUtils.greet("Ada"));

console.log(appUtils.slugify("Hello World"));

// Hello, Ada!

// hello-world
Try It Yourself

How It Works

_.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

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'

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 _.

javascript
_.mixin({ foo: _.constant("foo") });



const lodash = _.runInContext();



lodash.mixin({ bar: lodash.constant("bar") });



console.log(_.isFunction(_.foo));       // true

console.log(_.isFunction(_.bar));       // false

console.log(lodash.isFunction(lodash.bar)); // true

How It Works

runInContext() clones Lodash into a separate function object. Mixins on that copy never appear on the original _—ideal for libraries shipped to many consumers.

🧠 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.

📝 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.
  • { chain: false } changes how mixed-in methods behave inside _('x').fn() sequences.
  • 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.

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.

💡 Best Practices

✅ Do

  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about _.mixin()

Use these points when extending Lodash safely.

5
Core concepts
🔗 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.

Practice _.mixin() in the Live Editor

Open the Try It editor, add custom helpers to Lodash, and experiment with the chain option.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful