Lodash slice vs Native Array slice Explained
While both Lodash’s _.slice and JavaScript's native
Array.prototype.slice extract a subset of elements from an
array between specified start and end indices, they differ in several
key implementation details. Lodash’s implementation introduces defensive
programming features, alters how sparse arrays are handled, directly
accommodates array-like objects, and adheres to a functional data-first
paradigm.
Safe Null and Undefined Handling
The native Array.prototype.slice method is an instance
method on the Array prototype. If you attempt to invoke it
on a variable that evaluates to null or
undefined, JavaScript throws a TypeError.
const list = null;
list.slice(0, 2); // Throws TypeError: Cannot read properties of nullLodash’s _.slice is built with defensive fallback
handling. If passed null or undefined, it
fails gracefully and returns an empty array:
_.slice(null, 0, 2); // Returns []Sparse Array Treatment
A major behavioral difference lies in how both methods handle sparse
arrays (arrays containing empty slots or "holes"). Native
slice preserves these empty slots:
const sparse = [1, , 3];
const nativeResult = sparse.slice(0, 3);
console.log(nativeResult); // [1, <1 empty item>, 3]
console.log(1 in nativeResult); // falseIn contrast, _.slice densifies the output. It reads the
empty slots as explicit undefined values:
const sparse = [1, , 3];
const lodashResult = _.slice(sparse, 0, 3);
console.log(lodashResult); // [1, undefined, 3]
console.log(1 in lodashResult); // trueSupport for Array-Like Objects
Native slice can only be invoked directly on actual
arrays. To use it on array-like objects (such as arguments,
NodeList, or custom objects with a length
property), you must explicitly borrow the method:
function getArgs() {
return Array.prototype.slice.call(arguments, 1);
}Lodash natively accepts array-like structures as its primary argument
without requiring Function.prototype.call:
function getArgs() {
return _.slice(arguments, 1);
}Functional Signature
Native slice relies on the this context to
identify the target array. Lodash uses an explicit
(array, start, end) signature where the data is the first
parameter. This design allows _.slice to integrate
seamlessly into functional compositions and pipelines, particularly when
using Lodash's curried variants (lodash/fp).
Performance
Native Array.prototype.slice is heavily optimized by
modern JavaScript engines like V8 and runs faster in most runtime
environments. Lodash’s _.slice incurs minor overhead due to
input validation, bounds-checking algorithms, and dense array
normalization.