Lodash _.stubArray() 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 _.stubArray() as a small factory that returns fresh empty arrays—ideal for defaults, fallbacks, and functional callbacks.

01

Core Syntax

_.stubArray()

02

Returns []

Real array.

03

Fresh each call

New reference.

04

Defaults

Param fallbacks.

05

As callback

Pass reference.

06

Stub family

With constant.

What Is _.stubArray()?

_.stubArray is a function with no parameters that returns an empty array. Call it as _.stubArray() when you need [] right now, or pass _.stubArray (without parentheses) when another API wants a function that produces empty arrays—similar to writing () => [].

💡
Beginner tip — not an “array-like” object

_.stubArray() returns a normal JavaScript array ([]) with all standard array methods— not a plain object pretending to be an array.

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

📝 Syntax

Invoke with no arguments:

javascript
_.stubArray()

Syntax Rules

  • _.stubArray — the function reference (pass to callbacks).
  • _.stubArray() — call it to get [] immediately.
  • Fresh arrays — each call returns a new empty array instance.
  • Zero args — ignores any arguments if callers pass them anyway.
  • Length zero_.stubArray().length === 0.
javascript
import stubArray from "lodash/stubArray";



stubArray();

// []

⚡ Quick Reference

TaskCode patternNotes
Get empty array_.stubArray()Immediate []
Default parameterfn(x = _.stubArray())When omitted
Fallback returnreturn data || _.stubArray()Always array
Callback ref_.times(3, _.stubArray)Fn reference
Arrow equivalent() => []Same idea
Shared reference_.constant([])Same [] each call
Returns
[]

Empty array

Type
Function

Zero-arg

Each call
New []

Fresh ref

Category
Util

Stub

🧰 Parameters

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

arguments None

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

_.stubArray()
return Array

Empty array []—truthy in JavaScript but with length === 0.

[]
reference Per call

Successive calls return different array objects—safe to mutate independently.

a !== b
as callback Pattern

Pass _.stubArray without () when an iteratee should produce [].

_.times(n, _.stubArray)

Need a fixed value other than arrays? See _.constant() and the other stub helpers in this series.

Examples Gallery

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

📚 Getting Started

Call stubArray and inspect the result.

Example 1 — Basic empty array

The simplest use—get [] in one expression.

javascript
const empty = _.stubArray();



console.log(empty);

console.log(Array.isArray(empty));

console.log(empty.length);

// []

// true

// 0
Try It Yourself

How It Works

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

Example 2 — Fresh array each call

Two calls produce different references—safe for independent mutation.

javascript
const a = _.stubArray();

const b = _.stubArray();



a.push(1);



console.log(a);

console.log(b);

console.log(a === b);

// [1]

// []

// false
Try It Yourself

How It Works

Unlike _.constant([]), which reuses one array, stubArray allocates a new [] per invocation.

📈 Practical Patterns

Defaults, merging, and safe fallbacks.

Example 3 — Default function parameter

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

javascript
function processItems(items = _.stubArray()) {

  return items.length;

}



console.log(processItems());

console.log(processItems([1, 2, 3]));

// 0

// 3

How It Works

Plain items = [] also works in modern JS; stubArray signals intent in Lodash-heavy codebases.

Example 4 — Merge with optional second array

Default both sides to empty so concat always succeeds.

javascript
function mergeArrays(

  array1 = _.stubArray(),

  array2 = _.stubArray()

) {

  return array1.concat(array2);

}



console.log(mergeArrays([1, 2, 3]));

console.log(mergeArrays());

// [1, 2, 3]

// []
Try It Yourself

How It Works

Only one array passed? The other default kicks in as []—no undefined.concat errors.

Example 5 — Fallback return value

Guarantee an array type even when data is missing.

javascript
function fetchTags(apiResult) {

  const tags = apiResult && apiResult.tags;

  return tags || _.stubArray();

}



console.log(fetchTags({ tags: ["js", "lodash"] }));

console.log(fetchTags(null));

// ["js", "lodash"]

// []

How It Works

Callers can always call .map on the result without null checks—empty means “no tags.”

🚀 Beyond the Basics

stubArray vs alternatives in the stub family.

Example 6 — stubArray vs [] vs constant vs arrow

Pick the right empty-array tool for the job.

javascript
// Immediate empty array

console.log(_.stubArray());



// 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 stubArray

console.log((() => [])() instanceof Array);

// true for all [] producers

When to use which

Use stubArray for named functional style; [] or = [] when you prefer plain JavaScript; avoid mutating constant([]) results.

🧠 How _.stubArray() Works

1

Invoke stub

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

Call
2

Allocate []

Lodash returns a new empty array instance.

Create
3

Use as normal array

Push, map, concat, spread—standard array operations apply.

Consume
=

Empty array

length === 0, ready for safe defaults and fallbacks.

📝 Notes

  • Returns a real array—not an “array-like” plain object.
  • Each _.stubArray() call creates a separate []—unlike _.constant([]).
  • Pass _.stubArray without parentheses when an API expects a zero-arg producer function.
  • return items || _.stubArray() treats empty array as truthy—use nullish coalescing if [] should be preserved.
  • Part of the stub helper family—next: _.stubFalse().
  • Previous in the series: _.runInContext().

Conclusion

_.stubArray() is a tiny but expressive helper: a function that always produces fresh empty arrays. Use it for defaults, merge helpers, and fallback returns when you want Lodash-flavored clarity over raw [].

Remember the distinction from _.constant([])—stubArray is for independent empty arrays; constant is for a fixed shared value.

💡 Best Practices

✅ Do

  • Use _.stubArray() for readable empty-array defaults in Lodash code
  • Return _.stubArray() when APIs must always yield an array type
  • Pass _.stubArray as a callback when iteratees should produce []
  • Prefer stubArray over constant([]) when results may be mutated
  • Combine with optional parameters for concat/merge helpers

❌ Don’t

  • Call it expecting a shared singleton array across calls
  • Confuse with array-like objects—it returns a true Array
  • Use || stubArray() when empty arrays are valid data—use ??
  • Reach for stubArray when a plain = [] default is clearer for your team
  • Mutate arrays returned from _.constant([]) thinking they are fresh

Key Takeaways

Knowledge Unlocked

Five things to remember about _.stubArray()

Use these points for empty-array 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

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

Lodash documents _.times(2, _.stubArray) alongside other stub helpers—passing _.stubArray by reference lets _.times invoke it each iteration and collect separate empty arrays.

Practice _.stubArray() in the Live Editor

Try basic empty arrays, fresh-reference checks, and merge-with-defaults 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