Lodash _.constant() Method

Beginner
⏱️ 7 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 _.constant() to build functions that always return one fixed value—no matter what arguments callers pass.

01

Core Syntax

Wrap any value: const fn = _.constant(value).

02

Ignores Args

Callers can pass anything—return stays the same.

03

With _.cond

Default branch handlers and fixed outcomes.

04

Test Mocks

Stub callbacks that return preset data.

05

Stub Helpers

Relation to _.stubTrue and friends.

06

vs defaultTo

Fixed fn vs nullish fallback value.

What Is _.constant()?

_.constant() is a Lodash util helper that turns any value into a zero-argument function (ignoring extras) returning that value every time. APIs that expect callbacks—_.map, event hooks, or _.cond handlers—often need a function even when the result never changes. _.constant(42) is cleaner than writing () => 42 repeatedly in Lodash-heavy code.

💡
Beginner tip

Think of _.constant("OK") as a vending machine that always dispenses the same item. Shoppers can press different buttons (arguments), but the output never changes.

It is a small building block behind Lodash stub utilities and default branches in functional conditionals—not a replacement for real business logic, but a handy adapter when a function signature is required.

📝 Syntax

Pass the value you want every call to return:

javascript
_.constant(value)

Syntax Rules

  • value — any JavaScript value: number, string, boolean, object, array, or undefined.
  • Return value — a new function; each invocation returns the captured value.
  • Arguments ignoredfn(), fn(1, 2, 3) all return the same thing.
  • Reference types — objects and arrays are returned by reference, not cloned.
  • Not lazy — the value is fixed when you call _.constant(), not recomputed per call.
javascript
import constant from "lodash/constant";

const always42 = constant(42);

console.log(always42());      // 42
console.log(always42(100));   // 42 — arguments ignored

⚡ Quick Reference

TaskCode patternResult
Number constant_.constant(42)Fn always returns 42
String constant_.constant("OK")Fn always returns "OK"
Object payload_.constant({ ok: true })Same object reference
cond default[_.stubTrue, _.constant("Other")]Fixed fallback result
Equivalent stub_.stubTrue === _.constant(true)**Same behavior
Native equivalent() => 42Arrow closure
Returns
Function

Fixed-value fn

Args
Ignored

Any call signature

Related
stubTrue

Built on constant

Category
Util

Function factories

🧰 Parameters

The single argument to _.constant():

value Required

The value the generated function will return on every invocation. Can be any type including null and undefined.

_.constant("done")
return value Function

A function with no logic—only a closure over value. Safe to pass wherever a callback is expected.

const fn = _.constant(0)
objects / arrays Important

The same reference is returned each call. Clone first with _.cloneDeep if callers might mutate the payload.

_.constant(_.cloneDeep(cfg))
not a default param Tip

For missing function arguments use a normal default: callback = () => {}. Constant wraps a return value, not a parameter default expression.

fn(cb = () => {})

Need nullish fallbacks on data values? Use _.defaultTo() next—not _.constant().

Examples Gallery

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

📚 Getting Started

Create fixed-return functions and see arguments ignored.

Example 1 — Always return 42

The classic intro: a function that ignores every argument and returns the captured number.

javascript
const always42 = _.constant(42);

console.log(always42());       // 42
console.log(always42(100));    // 42
console.log(always42(1, 2, 3)); // 42
Try It Yourself

How It Works

Lodash closes over 42 once when you call _.constant(42). The returned function has no parameters in its logic—it always yields that closed-over value.

Example 2 — Fixed string response

Return the same message from a handler registered in a plugin-style API.

javascript
const alwaysHello = _.constant("Hello");

function registerGreeting(fn) {
  console.log(fn());
}

registerGreeting(alwaysHello);           // "Hello"
registerGreeting(_.constant("Hello"));   // "Hello"

How It Works

When an API requires a function but your implementation never varies, _.constant satisfies the contract without boilerplate.

📈 Practical Patterns

Pair with _.cond, mock tests, and shared object payloads.

Example 3 — Default result in _.cond

Use _.constant as the handler for the catch-all branch alongside _.stubTrue.

javascript
const labelSize = _.cond([
  [(n) => n < 10,  _.constant("Small")],
  [(n) => n < 20,  _.constant("Medium")],
  [(n) => n < 30,  _.constant("Large")],
  [_.stubTrue,       _.constant("Huge")]
]);

console.log(labelSize(5));   // "Small"
console.log(labelSize(35));  // "Huge"
Try It Yourself

How It Works

Each handler could be () => "Small"; _.constant("Small") reads clearly in cond tables and matches Lodash stub style.

Example 4 — Mock API callback in tests

Inject a callback that always resolves with a fixed payload—useful for unit tests and demos.

javascript
const mockApiResponse = _.constant({
  success: true,
  data: "Mock data"
});

function fetchUser(id, callback) {
  // In production: real HTTP call
  callback(mockApiResponse());
}

fetchUser(1, (result) => {
  console.log(result.success, result.data);
});
// true Mock data

// Test with the constant directly as callback
fetchUser(1, () => mockApiResponse());
Try It Yourself

How It Works

The mock object is created once. Every call to mockApiResponse() returns that same object reference—ideal for predictable test doubles.

Example 5 — Object reference caveat

Constants over objects share one reference—mutations affect later calls.

javascript
const payload = { count: 0 };
const getPayload = _.constant(payload);

const a = getPayload();
a.count = 5;

const b = getPayload();
console.log(b.count); // 5 — same object

// Safer: constant over a primitive
const alwaysZero = _.constant(0);
console.log(alwaysZero()); // 0

How It Works

_.constant does not clone. For immutable snapshots use Object.freeze, _.cloneDeep, or constant primitives instead.

🚀 Beyond the Basics

Compare stub helpers, arrows, and defaultTo.

Example 6 — constant vs stubTrue vs arrow vs defaultTo

Pick the right helper— they solve different problems.

javascript
// constant — any fixed return value
console.log(_.constant(42)());        // 42

// stubTrue — sugar for constant(true)
console.log(_.stubTrue());              // true
console.log(_.constant(true)());      // true

// arrow — native equivalent
console.log((() => 42)());            // 42

// defaultTo — NOT a function factory; nullish fallback
console.log(_.defaultTo(null, "guest")); // "guest"
console.log(_.defaultTo("Ada", "guest")); // "Ada"

When to prefer constant

Use _.constant() when you need a function that always returns one value. Use _.defaultTo() when you have a nullable value and want a fallback—not a callback.

🗸 How _.constant() Works

1

Capture value

Lodash closes over the value you pass to _.constant().

Setup
2

Return wrapper fn

You get a function with no conditional logic—only the closure.

Factory
3

Invoke anytime

Callers may pass zero or many arguments—all ignored.

Call
=

Same value every time

The closed-over value is returned on every invocation.

📝 Notes

  • _.constant() creates a function, not the value itself—call it with () when you need the payload.
  • Object and array constants return the same reference; clone if callers mutate results.
  • Do not use as a default parameter value for strings—use name = "Guest" directly instead.
  • _.stubTrue, _.stubFalse, _.stubArray, and _.stubObject are specialized constants.
  • For nullable data fallback use _.defaultTo(), not constant.
  • Pairs naturally with _.cond() fixed-outcome handlers.

Conclusion

_.constant() is a tiny but useful factory: turn any value into a function that always returns it. Reach for it in cond tables, test mocks, and anywhere a callback slot needs a predictable, argument-proof result.

Remember reference semantics for objects, and do not confuse it with _.defaultTo()—that helper fixes nullish data, not function signatures.

💡 Best Practices

✅ Do

  • Use for cond handlers that return fixed strings or numbers
  • Use for test doubles and demo callbacks with stable payloads
  • Prefer primitives or frozen objects when immutability matters
  • Reach for _.stubTrue when you specifically need constant true
  • Document why a no-op callback returns a fixed value

❌ Don’t

  • Wrap _.constant inside default parameters for plain strings
  • Assume object constants are deep-cloned snapshots
  • Replace _.defaultTo with constant—they solve different jobs
  • Use constant when real logic should inspect arguments
  • Overuse where a literal default argument is clearer

Key Takeaways

Knowledge Unlocked

Five things to remember about _.constant()

Use these points when you need fixed-return functions.

5
Core concepts
🚫 02

Ignores args

Any call signature.

Behavior
📋 03

cond

Fixed handlers.

Pattern
🧪 04

Mocks

Test callbacks.

Practical
05

defaultTo

Different helper.

Next step

❓ Frequently Asked Questions

_.constant(value) returns a new function. Every time you call that function—with zero arguments or many—it returns the same value that was passed to _.constant(). Arguments are completely ignored.
_.constant() always returns its fixed value. _.defaultTo(value, default) picks value unless value is null or undefined. Use constant for function factories; use defaultTo for fallback values on nullable data.
No. If you pass an object or array, the returned function always returns the same reference. Mutating that object elsewhere changes what future calls return. Pass primitives or freeze objects when you need immutability.
Lodash stub helpers like _.stubTrue, _.stubFalse, and _.stubArray are implemented with _.constant() internally. stubTrue is equivalent to _.constant(true).
Use it for default handlers in _.cond, no-op callbacks, test mocks that return fixed payloads, and anywhere an API expects a function but you only need a fixed return value.
Yes for simple cases. _.constant() is slightly more explicit in functional Lodash code and matches stub/cond patterns. Arrow functions are fine when you do not need a named lodash helper.
Did you know?

Lodash’s stub utilities are thin wrappers around _.constant(): stubTrue is constant(true), stubArray is constant([]), and stubObject is constant({}). Learning constant unlocks the whole stub family.

Practice _.constant() in the Live Editor

Open the Try It editor, run the examples, and experiment with fixed-return callbacks.

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