How Lodash _.drop Handles Frozen Arrays

In the Lodash JavaScript library, passing a globally frozen array to the _.drop method works without throwing any errors because the operation is purely non-mutating. Instead of modifying the frozen source array in place, _.drop reads its elements and returns a shallow copy containing the remaining items in a brand-new, unfrozen array.

Non-Mutating Execution

JavaScript's Object.freeze() makes an object or array immutable, preventing any additions, deletions, or index-based property reassignments. Attempting to run mutating methods such as Array.prototype.shift() or Array.prototype.splice() on a frozen array results in a runtime TypeError in strict mode.

Lodash's _.drop avoids this limitation entirely. Under the hood, _.drop relies on an internal slicing mechanism (baseSlice), which behaves similarly to native Array.prototype.slice(). It calculates the start index based on the number of elements to drop, reads the values from the original array, and pushes them into a newly allocated array instance.

Practical Example

Consider the following example using a globally frozen array:

// Define a globally frozen array
const frozenList = Object.freeze(['alpha', 'beta', 'gamma', 'delta']);

// Drop the first two elements
const result = _.drop(frozenList, 2);

console.log(result); 
// Output: ['gamma', 'delta']

console.log(Object.isFrozen(frozenList)); 
// Output: true

console.log(Object.isFrozen(result)); 
// Output: false

State of the Returned Array

The resulting array from _.drop has the following characteristics:

  1. New Reference: It does not share the memory reference of the original array.
  2. Mutable by Default: The new array is not frozen. You can push, pop, or modify elements on the returned array without restrictions unless you explicitly call Object.freeze() on it.
  3. Shallow Copy Behavior: While the array structure itself is cloned, any non-primitive elements (such as nested objects or child arrays) are copied by reference. If the nested objects inside the frozen array were themselves frozen, their inner properties will remain immutable in the output array.