Lodash _.tail on Empty Array Behavior
When executing the _.tail method on a strictly empty
array ([]) in the Lodash JavaScript library, the function
safely returns a new empty array ([]). It does not throw a
TypeError, crash, or return null or
undefined. This article breaks down the exact mechanics
behind this behavior, the underlying implementation, and what developers
should expect when working with empty collections in Lodash.
The Return Value
Calling _.tail([]) yields an empty array:
const _ = require('lodash');
const result = _.tail([]);
console.log(result); // Output: []
console.log(Array.isArray(result)); // Output: true
console.log(result.length); // Output: 0Because _.tail creates a shallow slice of the provided
array, the returned empty array is a completely new array instance in
memory. Comparing the original empty array to the resulting empty array
using strict reference equality (===) evaluates to
false.
const input = [];
const output = _.tail(input);
console.log(input === output); // Output: falseHow Lodash Implements
_.tail
The purpose of _.tail(array) is to retrieve all elements
of an array except the first one. Lodash implements this
defensively:
- Length Check: Lodash determines the length of the
input collection. For an empty array, the length is
0. - Base Slicing: The operation resolves to a slicing
logic equivalent to
array.slice(1). - Empty Bounds: When standard JavaScript slicing is
performed on an array where the start index (
1) exceeds the array's length (0), the specification dictates that an empty array is returned.
Lodash relies on internal helper functions such as
baseSlice to copy elements starting at index 1
up to length. If length is 0, no
iterations occur, and an empty array is returned immediately.
Differences from Alternative Methods
Understanding this outcome clarifies how _.tail compares
to standard JavaScript patterns:
- Native
.slice(1): Running[].slice(1)produces the exact same result ([]). - Array Destructuring: Running
const [, ...rest] = []also creates an empty array (rest = []). - Direct Indexing: Attempting to manually grab
remaining elements via indices on an empty array can lead to
undefinedvalues, whereas_.tailguarantees that the returned value remains an iterable array structure.
Because _.tail([]) safely produces an empty array
without runtime errors, it can be seamlessly chained or used in
functional pipelines without requiring explicit pre-checks for array
length.