Lodash _.defaultTo() Method

Beginner
⏱️ 8 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 _.defaultTo() to supply fallbacks when values are null or undefined—without accidentally wiping out 0 or empty strings.

01

Core Syntax

_.defaultTo(value, fallback) in one call.

02

Nullish Only

Replaces null and undefined—not all falsy values.

03

Keep 0 & ""

Zero and empty string stay intact.

04

Config Defaults

Fill missing API and app settings safely.

05

vs || and ??

Pick the right fallback operator.

06

vs defaults

Single value vs object merge helper.

What Is _.defaultTo()?

_.defaultTo() is a Lodash util helper that returns a fallback value only when the first argument is null or undefined. Otherwise it returns the original value unchanged. It is the Lodash expression of nullish coalescing—cleaner than writing value != null ? value : fallback repeatedly in config loaders and data mappers.

💡
Beginner tip — empty string is not missing

_.defaultTo("", "guest") returns "", not "guest". An empty string is a deliberate value (user cleared the field). Only use || if you truly want to replace empty strings too.

Reach for _.defaultTo() when optional properties from JSON, query strings, or database rows may be absent, but legitimate falsy values like 0 or false should survive.

📝 Syntax

Pass the value to test and the fallback to use when it is nullish:

javascript
_.defaultTo(value, defaultValue)

Syntax Rules

  • value — the value you have (may be null or undefined).
  • defaultValue — returned only when value is null or undefined.
  • Falsy but kept0, "", false, and NaN are not replaced.
  • Return value — either value or defaultValue (not a function).
  • Native twinvalue ?? defaultValue behaves the same way.
javascript
import defaultTo from "lodash/defaultTo";

const name = defaultTo(undefined, "Guest");
// -> "Guest"

const count = defaultTo(0, 10);
// -> 0 (zero is kept)

⚡ Quick Reference

Input value_.defaultTo(v, "fb")v || "fb"
undefined"fb""fb"
null"fb""fb"
"""""fb"
00"fb"
falsefalse"fb"
"Ada""Ada""Ada"
Triggers
null | undefined

Nullish only

Native
??

Same behavior

Object merge
_.defaults

Different helper

Category
Util

Value fallback

🧰 Parameters

Arguments to _.defaultTo() and what each controls:

value Required

The value to return when it is defined (including empty string, zero, and false). Lodash checks only for null and undefined.

_.defaultTo(user.name, "Guest")
defaultValue Required

The fallback when value is nullish. Can be any type—string, number, object, or even null if you intentionally want null as the default.

_.defaultTo(cfg.timeout, 5000)
return value value | default

Not a function—immediately resolves to one of the two inputs. Safe to embed in object literals and return statements.

return _.defaultTo(n, 0)
not for "" Important

To treat empty string as missing, combine checks: value === "" ? fallback : _.defaultTo(value, fallback) or use || deliberately.

_.defaultTo("", "x") // ""

For filling multiple missing object properties at once, see _.defaults() in the object category—not _.defaultTo().

Examples Gallery

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

📚 Getting Started

Replace null and undefined while keeping other values intact.

Example 1 — Fallback for null and undefined

When a property is missing from parsed JSON, supply a display name.

javascript
console.log(_.defaultTo(undefined, "Guest")); // "Guest"
console.log(_.defaultTo(null, "Guest"));      // "Guest"
console.log(_.defaultTo("Ada", "Guest"));     // "Ada"
Try It Yourself

How It Works

Lodash uses a nullish test internally—same idea as value ?? "Guest". Defined strings pass through unchanged.

Example 2 — Zero and empty string are kept

Unlike ||, _.defaultTo() preserves meaningful falsy values.

javascript
console.log(_.defaultTo(0, 10));        // 0
console.log(_.defaultTo("", "empty"));  // ""
console.log(_.defaultTo(false, true));  // false

// || would replace all of the above with the fallback
console.log(0 || 10);       // 10
console.log("" || "empty"); // "empty"
Try It Yourself

How It Works

Page size 0, an cleared text field "", and a feature flag false are valid states—defaultTo respects them.

📈 Practical Patterns

Configuration, data cleanup, and URL/query parsing.

Example 3 — Application settings

Merge user settings with defaults when optional keys are nullish.

javascript
const settings = {
  timeout: 3000,
  maxRetries: null,
  theme: undefined
};

const apiTimeout = _.defaultTo(settings.timeout, 5000);
const retries    = _.defaultTo(settings.maxRetries, 3);
const theme      = _.defaultTo(settings.theme, "light");

console.log({ apiTimeout, retries, theme });
// { apiTimeout: 3000, retries: 3, theme: "light" }
Try It Yourself

How It Works

timeout: 3000 is kept. maxRetries: null and missing theme pick up defaults. For many keys at once, _.defaults() is an alternative.

Example 4 — Sanitize nullable record fields

Map API rows so null names and emails get readable placeholders—without touching valid empty strings if present.

javascript
const rows = [
  { id: 1, name: "Alice", email: "alice@example.com" },
  { id: 2, name: null, email: "bob@example.com" },
  { id: 3, name: "Charlie", email: undefined }
];

const sanitized = _.map(rows, (entry) => ({
  id: entry.id,
  name:  _.defaultTo(entry.name, "Unknown"),
  email: _.defaultTo(entry.email, "No email provided")
}));

console.log(sanitized[1].name);  // "Unknown"
console.log(sanitized[2].email); // "No email provided"

How It Works

Only nullish database fields are replaced. If a user intentionally saved name: "", defaultTo would keep the empty string.

Example 5 — Query parameter with page number

Parse an optional page index—0 must remain valid for the first page.

javascript
function parsePageParam(raw) {
  if (raw === undefined || raw === null) {
    return _.defaultTo(undefined, 1);
  }
  return Number(raw);
}

console.log(parsePageParam(undefined)); // 1 (default first page)
console.log(parsePageParam("0"));       // 0 (valid index)
console.log(parsePageParam("3"));      // 3

How It Works

Using raw || 1 would turn page 0 into page 1. defaultTo applies only when the param is absent, not when it parses to zero.

🚀 Beyond the Basics

Compare operators and related Lodash helpers.

Example 6 — defaultTo vs ?? vs || vs _.defaults

Choose the fallback tool that matches your intent.

javascript
const v = 0;

console.log(_.defaultTo(v, 99)); // 0
console.log(v ?? 99);            // 0
console.log(v || 99);            // 99

// Object-level: fill undefined keys on destination
const opts = { timeout: undefined, retries: 2 };
_.defaults(opts, { timeout: 5000, retries: 3, theme: "light" });
// opts -> { timeout: 5000, retries: 2, theme: "light" }

When to prefer defaultTo

Use _.defaultTo() for single-value nullish fallback in Lodash pipelines. Use ?? in modern JS without Lodash. Use _.defaults() when merging whole option objects.

🧠 How _.defaultTo() Works

1

Receive value + default

Lodash takes the candidate value and the fallback to use if missing.

Input
2

Nullish check

Tests whether value is null or undefined—and nothing else.

Test
3

Pick result

Return defaultValue when nullish; otherwise return value unchanged.

Return
=

Safe fallback

Falsy-but-valid values like 0 and "" survive the check.

📝 Notes

  • Only null and undefined trigger the fallback—not empty strings or zero.
  • Equivalent to native value ?? defaultValue for the same inputs.
  • Do not nest multiple _.defaultTo() calls—one per value is clearer.
  • Centralize shared defaults in a constants module for consistency across the app.
  • For whole-object templates use _.defaults(); for fixed-return callbacks use _.constant().
  • If you need to replace empty strings, add an explicit check or use || knowingly.

Conclusion

_.defaultTo() is a small, precise helper: when data might be missing (null or undefined), supply a fallback without clobbering legitimate 0, false, or "" values.

Pair it with clear default constants, compare consciously with ||, and reach for _.defaults() when you are merging entire options objects.

💡 Best Practices

✅ Do

  • Use for nullable API fields and optional config keys
  • Prefer defaultTo or ?? over || when 0 and "" are valid
  • Keep default values meaningful ("Guest", 5000 ms, etc.)
  • Document shared defaults in one constants object
  • Combine with _.map when normalizing arrays of records

❌ Don’t

  • Expect empty string to become the fallback automatically
  • Replace || when you intentionally want all falsy values defaulted
  • Nest defaultTo calls—use one clear expression per value
  • Confuse defaultTo with _.constant or _.defaults
  • Use defaultTo for deep nested object merging

Key Takeaways

Knowledge Unlocked

Five things to remember about _.defaultTo()

Use these points when choosing fallback logic.

5
Core concepts
🔢 02

Keep 0

Zero stays zero.

Critical
📝 03

Keep ""

Empty string OK.

Pitfall
🔄 04

?? twin

Same as coalescing.

Native
05

defaults

For object merge.

Related

❓ Frequently Asked Questions

_.defaultTo(value, defaultValue) returns value when it is not null and not undefined. If value is null or undefined, it returns defaultValue instead. It is a concise nullish fallback helper.
No. Only null and undefined trigger the fallback. An empty string, 0, false, and NaN are valid values and are returned as-is. Use logical OR (||) only when you intend to replace all falsy values.
The || operator replaces any falsy value (0, '', false, null, undefined, NaN). _.defaultTo() replaces only null and undefined—so 0 and '' are preserved, which is usually safer for user input and numeric settings.
They behave the same for null and undefined. ?? is native ES2020 syntax: value ?? default. _.defaultTo(value, default) is the Lodash equivalent and reads well in lodash-heavy pipelines.
_.defaultTo() works on a single value. _.defaults() merges objects, filling missing undefined properties on a destination from source objects. Use defaultTo per field; use defaults for whole object templates.
_.defaultTo() picks between two values based on nullish check. _.constant() returns a function that always returns one fixed value. defaultTo is for data fallbacks; constant is for function factories.
Did you know?

Before ES2020’s ?? operator, _.defaultTo() was a popular way to avoid the || trap where 0 and "" were accidentally replaced. In new code you can use either—behavior matches for null and undefined.

Practice _.defaultTo() in the Live Editor

Open the Try It editor, run the examples, and experiment with nullish fallback logic.

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