Lodash _.attempt() Method

Beginner
5 min read
Updated: Nov 2026
5 examples
Util

Definition

Attempts to invoke func, returning either the result or the caught error object. Extra arguments are passed to func. Part of Lodash Util since 3.0.0 (stable — not deprecated).

Note: Synchronous only — it does not await Promises. Pair the return value with _.isError().

Syntax

Call _.attempt. Start with this line.

Lodash
_.attempt(func, [args])
CallWhat it does
_.attempt(func, [args])Primary signature.
_.attempt(...)Call the util helper.

Prefer import attempt from "lodash/attempt" when you want a smaller bundle.

Library declarations
Lodash
_.attempt(func, [args])

Parameters

ParameterDescription
funcRequired. Function to invoke
argsOptional. Arguments forwarded to func

Return Value

Return ValueDescription
*func result, or the caught error object

Lodash Examples

Example 1 — Official: Invalid Selector

Catch a DOM exception and fall back to an empty list.

Lodash
var elements = _.attempt(function (selector) {
  return document.querySelectorAll(selector);
}, '>_>');

if (_.isError(elements)) {
  elements = [];
}

console.log(elements);
// → []
Try It Yourself

How It Works

  1. Call. Lodash invokes the function with '>_>'.
  2. Throw. Invalid CSS selector makes querySelectorAll throw.
  3. Catch. _.attempt returns the Error instead of crashing.
  4. Fallback. _.isError is true → replace with [].

Example 2 — Successful Return

When nothing throws, you get the function’s return value.

Lodash
function add(a, b) {
  return a + b;
}

var result = _.attempt(add, 10, 32);

console.log(result);             // 42
console.log(_.isError(result));  // false
Try It Yourself

How It Works

  1. Forward args. 10 and 32 become add(10, 32).
  2. No throw. The sum 42 passes through unchanged.
  3. Check. _.isError(42) is false.
  4. Use. Treat result as a normal number.

Example 3 — Safe JSON.parse

Invalid JSON throws SyntaxError — attempt turns it into a value you can handle.

Lodash
function parseConfig(raw) {
  var parsed = _.attempt(JSON.parse, raw);
  if (_.isError(parsed)) {
    return { theme: 'light' };
  }
  return parsed;
}

console.log(parseConfig('{"theme":"dark"}'));
// → { theme: 'dark' }

console.log(parseConfig('{ bad'));
// → { theme: 'light' }
Try It Yourself

How It Works

  1. Parse. _.attempt(JSON.parse, raw) forwards the string.
  2. Valid. Good JSON returns the object.
  3. Invalid. Bad JSON throws → attempt returns the Error.
  4. Fallback. _.isError picks a default config.

Example 4 — Thrown Error as a Value

Any thrown Error becomes the return value — your script keeps running.

Lodash
function risky() {
  throw new Error('Something went wrong');
}

var result = _.attempt(risky);

if (_.isError(result)) {
  console.log(result.message);
}
// → "Something went wrong"
Try It Yourself

How It Works

  1. Invoke. risky throws immediately.
  2. Catch. Lodash returns the Error object.
  3. Detect. _.isError(result) is true.
  4. Read. Use result.message for a clear log line.

Example 5 — Map Without Stopping the Batch

One bad row should not abort the whole list.

Lodash
function parseRow(row) {
  if (!row.payload) {
    throw new Error('Missing payload');
  }
  return JSON.parse(row.payload);
}

var rows = [
  { id: 1, payload: '{"ok":true}' },
  { id: 2, payload: null },
  { id: 3, payload: '{"n":5}' }
];

var results = _.map(rows, function (row) {
  return _.attempt(parseRow, row);
});

console.log(_.isError(results[0])); // false
console.log(_.isError(results[1])); // true
console.log(_.isError(results[2])); // false
Try It Yourself

How It Works

  1. Per item. Each row is wrapped in _.attempt.
  2. Row 1 & 3. Valid payload → parsed objects.
  3. Row 2. Missing payload throws → Error in the array.
  4. Continue. The map finishes; partition successes later.

Browser & Runtime Support

_.attempt is a Lodash Util helper since 3.0.0. It runs anywhere Lodash runs — modern browsers (CDN or bundle) and Node.js / Bun / Deno with npm install lodash.

✓ Stable · Lodash 3.0.0+

_.attempt()

Available in [email protected] full builds and the lodash/attempt modular import. Works in evergreen browsers and current Node LTS when Lodash is installed.

100% With Lodash 3.0+
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
_.attempt Lodash 3.0.0+

Bottom line: Safe for production once Lodash is loaded. Prefer import attempt from "lodash/attempt" for smaller bundles. Use it for small synchronous risky calls; use native async/await for Promises.

Frequently Asked Questions

_.attempt(func, …args) invokes func and returns its result, or the caught error object if it throws. Official use: wrap risky calls like document.querySelectorAll with an invalid selector.
Use _.isError(result). When true, treat result as the caught Error (read result.message). When false, result is the normal return value.
Yes. Extra arguments after func are forwarded: _.attempt(JSON.parse, text) calls JSON.parse(text).
try/catch is a statement block. _.attempt returns value-or-error as one expression, which is handy inside _.map() or other callbacks.
No. It only catches synchronous throws. Promise rejections need try/catch with await, or .catch().
Use import attempt from "lodash/attempt" or require("lodash/attempt"). Full build: import _ from "lodash" then _.attempt.

Next: _.bindAll()

Bind object methods so this stays correct when passed as callbacks.

_.bindAll() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

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.

10 people found this page helpful