Lodash dropRight When Count Exceeds Array Length
When using the _.dropRight method in the Lodash
JavaScript library with a count that exceeds the total length of the
target array, Lodash safely returns a new, empty array
([]). This operation does not throw an error, does not
produce undefined or null, and leaves the
original array completely unmodified.
Behavior and Output
The _.dropRight(array, [n=1]) function creates a slice
of an array with n elements removed from the end. Lodash
internally handles boundary conditions for the n parameter
by clamping or comparing it against the array's length.
When the specified count n is greater than or equal to
array.length, the function removes all available elements
from the end until no elements remain.
const _ = require('lodash');
const numbers = [1, 2, 3, 4, 5];
// Array length is 5, dropping 10 elements
const result = _.dropRight(numbers, 10);
console.log(result);
// Output: []
console.log(numbers);
// Output: [1, 2, 3, 4, 5] (Original array remains unchanged)Key Characteristics
- Return Value: It consistently returns an empty
array
[]rather than throwing an index out of bounds exception. - Immutability: The source array is not mutated; a new array reference is returned.
- Falsy and Edge Counts: If the count is equal to the
array length, the result is also
[]. If the count is negative, Lodash treats it as0and returns a shallow copy of the entire original array.