Lodash _.takeRight with NaN Count Parameter

When using the Lodash utility library, executing the _.takeRight method with a count parameter that evaluates to NaN results in an empty array ([]). This article explains the exact behavior of _.takeRight when encountering NaN, details how Lodash processes non-numeric arguments internally, and provides code examples illustrating the output.

The Return Value

If you pass NaN as the n (count) argument to _.takeRight, the function returns an empty array:

const _ = require('lodash');

const numbers = [10, 20, 30, 40, 50];

const result = _.takeRight(numbers, NaN);
console.log(result); // Output: []

Regardless of the length or contents of the input array, requesting NaN elements from the end will always yield [].

Why Lodash Returns an Empty Array

The _.takeRight(array, [n=1]) function extracts a slice of n elements from the end of an array. To determine the slice boundary, Lodash normalizes the input argument n using its internal toInteger conversion function:

  1. Default Handling: If n is undefined, Lodash falls back to its default value of 1.
  2. Number Coercion: If n is provided (and not undefined), it passes through toInteger(n).
  3. NaN Evaluation: Lodash's toInteger relies on toFinite. When toFinite receives NaN, it coerces the value to 0.

Because NaN converts to 0, Lodash interprets the call as _.takeRight(array, 0). Slicing zero elements from the end of an array returns an empty array.

Comparison with Other Falsy Values

Understanding how NaN interacts with _.takeRight is clearer when compared to other falsy or non-numeric arguments:

If your application logic dynamically calculates the slice count and produces NaN (such as via an invalid mathematical operation like 0 / 0 or parseInt('abc')), _.takeRight safely fails by returning [] rather than throwing an exception.