Lodash flattenDepth Negative Depth Behavior

When passing a negative depth integer to the _.flattenDepth method in the Lodash JavaScript library, the function does not flatten any nested arrays and instead returns a shallow clone of the original array. Lodash evaluates whether the target depth is strictly greater than zero before attempting to recursively unpack nested collections, causing any negative or zero value to bypass the flattening logic entirely.

How Lodash Handles Negative Depth

Internally, Lodash implements _.flattenDepth using a helper function named baseFlatten. During execution, the library checks the recursion condition with:

depth > 0 && predicate(value)

Because a negative integer (such as -1 or -5) fails the depth > 0 condition, Lodash never unpacks child arrays. Instead, it pushes the elements from the input array directly into a new output array as-is.

Code Example

The following example illustrates this behavior when passing different depth arguments:

const _ = require('lodash');

const nestedArray = [1, [2, [3, [4]], 5]];

// Standard flattening with depth 1
console.log(_.flattenDepth(nestedArray, 1));
// Output: [1, 2, [3, [4]], 5]

// Flattening with a negative depth integer
console.log(_.flattenDepth(nestedArray, -1));
// Output: [1, [2, [3, [4]], 5]]

// Flattening with zero
console.log(_.flattenDepth(nestedArray, 0));
// Output: [1, [2, [3, [4]], 5]]

Key Takeaways