Lodash dropWhile with Array-Like Objects and Prototypes
This article explores how Lodash’s _.dropWhile method
handles array-like objects and their prototype properties. When
processing an array-like object, _.dropWhile returns a
brand-new native JavaScript array, stripping away custom prototype
chains while selectively evaluating prototype-inherited indexed
properties during its execution.
How
_.dropWhile Interacts with Array-Like Objects
An array-like object in JavaScript is any object that possesses a
non-negative integer length property and indexed elements
(such as arguments, DOM NodeLists, or custom objects like
{ 0: 'a', 1: 'b', length: 2 }).
When _.dropWhile processes an array-like object:
- Iteration Relies on Standard Index Access: Lodash
reads elements sequentially from index
0up tolength - 1. Because it uses standard indexed property access (object[index]), JavaScript traverses the object's prototype chain if an index is not defined as an "own" property on the instance itself. - Evaluation of Inherited Indices: If an indexed property exists on the prototype rather than the instance, the predicate function will still receive and evaluate that inherited value. If the predicate returns true, that indexed value is dropped.
- Conversion to a Native Array: The output of
_.dropWhileis always a standard nativeArrayinstance.
What Happens to Prototype Properties?
Custom Prototype Methods and Non-Indexed Properties
Any non-indexed properties or custom functions attached to the input
object’s prototype (such as custom utility methods on a specialized
collection class) are completely lost. Because the return value is an
instance of Array, its prototype chain points exclusively
to Array.prototype. It does not retain or inherit any links
to the original object’s prototype constructor.
Indexed Properties on the Prototype
If the input object inherits indexed elements from its prototype chain that are not dropped by the predicate:
- Those inherited elements are copied into the newly constructed array.
- In the resulting array, these elements become standard "own"
properties indexed sequentially starting from
0. - They no longer maintain any dynamic link to the original prototype; modifying the original prototype afterward will not affect the resulting array.
Summary of Behavior
- Prototype Chain: Discarded. The output inherits
directly from
Array.prototype. - Non-Indexed Prototype Properties: Ignored and omitted from the returned result.
- Indexed Prototype Properties: Evaluated by the predicate via standard property resolution; surviving elements are flattened into own properties of the new native array.