Lodash _.stubObject() Method

Beginner
⏱️ 6 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 _.stubObject() as a small factory that returns fresh empty objects—ideal for defaults, fallbacks, and functional callbacks.

01

Core Syntax

_.stubObject()

02

Returns {}

Plain object.

03

Fresh each call

New reference.

04

Defaults

Config fallbacks.

05

As callback

Pass reference.

06

Stub family

With constant.

What Is _.stubObject()?

_.stubObject is a function with no parameters that returns an empty object. Call it as _.stubObject() when you need {} right now, or pass _.stubObject (without parentheses) when another API wants a function that produces empty objects—similar to writing () => ({}).

💡
Beginner tip — empty, not “undefined keys”

_.stubObject() returns a plain empty object {} with zero own properties—not an object pre-filled with keys set to undefined.

It sits in Lodash’s stub helper family alongside _.stubArray() and _.stubFalse()—small building blocks for readable functional code.

📝 Syntax

Invoke with no arguments:

javascript
_.stubObject()

Syntax Rules

  • _.stubObject — the function reference (pass to callbacks).
  • _.stubObject() — call it to get {} immediately.
  • Fresh objects — each call returns a new empty object instance.
  • Zero args — ignores any arguments if callers pass them anyway.
  • No keysObject.keys(_.stubObject()).length === 0.
javascript
import stubObject from "lodash/stubObject";



stubObject();

// {}

⚡ Quick Reference

TaskCode patternNotes
Get empty object_.stubObject()Immediate {}
Default parameterfn(opts = _.stubObject())When omitted
Fallback returnreturn data || _.stubObject()Always object
Callback ref_.times(2, _.stubObject)Fn reference
Arrow equivalent() => ({})Same idea
Shared reference_.constant({})Same {} each call
Returns
{}

Empty object

Type
Function

Zero-arg

Each call
New {}

Fresh ref

Category
Util

Stub

🧰 Parameters

_.stubObject takes no parameters—only returns a value when invoked:

arguments None

No configuration. Call _.stubObject() with an empty argument list.

_.stubObject()
return Object

Empty plain object {}—truthy in JavaScript with zero own keys.

{}
reference Per call

Successive calls return different object instances—safe to mutate independently.

a !== b
as callback Pattern

Pass _.stubObject without () when an iteratee should produce {}.

_.times(n, _.stubObject)

Need a fixed shared object? See _.constant({}) and compare with the other stub helpers in this series.

Examples Gallery

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

📚 Getting Started

Call stubObject and inspect the result.

Example 1 — Basic empty object

The simplest use—get {} in one expression.

javascript
const empty = _.stubObject();



console.log(empty);

console.log(typeof empty);

console.log(Object.keys(empty).length);

// {}

// "object"

// 0
Try It Yourself

How It Works

stubObject is a named alias for the common pattern “give me an empty object now.”

Example 2 — Fresh object each call

Two calls produce different references—safe for independent mutation.

javascript
const a = _.stubObject();

const b = _.stubObject();



a.role = "admin";



console.log(a);

console.log(b);

console.log(a === b);

// { role: "admin" }

// {}

// false
Try It Yourself

How It Works

Unlike _.constant({}), which reuses one object, stubObject allocates a new {} per invocation.

📈 Practical Patterns

Defaults, merging, and safe fallbacks.

Example 3 — Default function parameter

When callers omit the options object, stub supplies an empty one for that invocation.

javascript
function processOptions(options = _.stubObject()) {

  return Object.keys(options).length;

}



console.log(processOptions());

console.log(processOptions({ theme: "dark", lang: "en" }));

// 0

// 2

How It Works

Plain options = {} also works in modern JS; stubObject signals intent in Lodash-heavy codebases.

Example 4 — Merge with optional overrides

Default to empty so _.assign always has a safe target object.

javascript
function buildConfig(overrides = _.stubObject()) {

  const defaults = { theme: "light", lang: "en" };

  return _.assign({}, defaults, overrides);

}



console.log(buildConfig({ theme: "dark" }));

console.log(buildConfig());

// { theme: "dark", lang: "en" }

// { theme: "light", lang: "en" }
Try It Yourself

How It Works

No overrides passed? The default empty object merges cleanly with your baseline config—no undefined property reads.

Example 5 — Nested placeholder in a schema

Reserve an empty object slot you can fill in later—common in user records and test mocks.

javascript
const user = {

  id: "user_123",

  name: "Jane Doe",

  profile: _.stubObject()

};



user.profile.bio = "Lodash learner";



console.log(user.profile);

// { bio: "Lodash learner" }

How It Works

profile starts as a mutable empty object—not null—so you can assign nested fields without extra guards.

🚀 Beyond the Basics

stubObject vs alternatives in the stub family.

Example 6 — stubObject vs {} vs constant vs arrow

Pick the right empty-object tool for the job.

javascript
// Immediate empty object

console.log(_.stubObject());



// ES default — also common

function fn(x = {}) { return x; }



// Same reference every call — caution if mutating

const shared = _.constant({});

console.log(shared() === shared());



// Arrow equivalent of stubObject

console.log((() => ({}))() instanceof Object);

// true for all {} producers

When to use which

Use stubObject for named functional style; {} or = {} when you prefer plain JavaScript; avoid mutating constant({}) results.

🧠 How _.stubObject() Works

1

Invoke stub

Call _.stubObject() or pass _.stubObject to an iteratee.

Call
2

Allocate {}

Lodash returns a new empty object instance.

Create
3

Use as normal object

Assign properties, merge with _.assign, spread—standard object operations apply.

Consume
=

Empty object

Object.keys(obj).length === 0, ready for safe defaults and fallbacks.

📝 Notes

  • Returns a plain object—not an array and not null.
  • Each _.stubObject() call creates a separate {}—unlike _.constant({}).
  • Pass _.stubObject without parentheses when an API expects a zero-arg producer function.
  • return meta || _.stubObject() treats empty object as truthy—use nullish coalescing if {} should be preserved.
  • Part of the stub helper family—next: _.stubString().
  • Previous in the series: _.stubFalse().

Conclusion

_.stubObject() is a tiny but expressive helper: a function that always produces fresh empty objects. Use it for defaults, merge helpers, nested placeholders, and fallback returns when you want Lodash-flavored clarity over raw {}.

Remember the distinction from _.constant({})—stubObject is for independent empty objects; constant is for a fixed shared value.

💡 Best Practices

✅ Do

  • Use _.stubObject() for readable empty-object defaults in Lodash code
  • Return _.stubObject() when APIs must always yield an object type
  • Pass _.stubObject as a callback when iteratees should produce {}
  • Prefer stubObject over constant({}) when results may be mutated
  • Combine with _.assign or _.defaults for config builders

❌ Don’t

  • Call it expecting a shared singleton object across calls
  • Confuse it with objects that have keys set to undefined—it returns truly empty {}
  • Use || stubObject() when empty objects are valid data—use ??
  • Reach for stubObject when a plain = {} default is clearer for your team
  • Mutate objects returned from _.constant({}) thinking they are fresh

Key Takeaways

Knowledge Unlocked

Five things to remember about _.stubObject()

Use these points for empty-object defaults and fallbacks.

5
Core concepts
🔄 02

Fresh ref

Each call.

Behavior
03

Defaults

Params.

Usage
📝 04

Callback

Pass ref.

Pattern
🛠 05

vs constant

Shared vs new.

Compare

❓ Frequently Asked Questions

_.stubObject is a zero-argument function. Calling _.stubObject() returns a new empty JavaScript object {}. It is a named helper for “always give me an empty object” in functional Lodash code.
{} is a value. _.stubObject is a function you call (or pass by reference) when an API expects a function that produces empty objects—default parameters, _.times, merge helpers, or fallback returns.
Yes—each _.stubObject() invocation returns a new empty object. That makes it safe for defaults you might mutate, unlike reusing one shared {} from _.constant({}).
Both belong to Lodash’s stub family. _.constant({}) returns the same object reference every call. _.stubObject() creates a new {} each time—better when callers might assign properties.
Yes: function fn(options = _.stubObject()) works. When the argument is omitted, Lodash’s stub runs and supplies a fresh empty object for that invocation.
Use it for empty-object fallbacks (return data || _.stubObject()), optional config parameters, nested placeholders in schemas, and anywhere you want () => ({}) with a descriptive Lodash name.
Did you know?

Lodash documents _.times(2, _.stubObject) in the official docs—passing _.stubObject by reference lets _.times invoke it each iteration and collect separate empty objects (e.g. [{}, {}]).

Practice _.stubObject() in the Live Editor

Try basic empty objects, fresh-reference checks, and config merge patterns.

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