Prefer Spread Over apply()
ID |
javascript.prefer_spread |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Best Practice |
Language |
JavaScript |
Tags |
best-practice, modernization |
Description
Reports calls of the form receiver.apply(thisArg, argsArray) where thisArg is null, undefined, or this. In those cases the caller is not actually rebinding this; apply is only being used to expand an array into the argument list. The modern, idiomatic equivalent is the spread operator: receiver(…argsArray).
Rationale
-
Spread is shorter and reads as "call
receiverwith these arguments", whereasapplyreads as "rebindthisand call". When the first argument isnull/undefined/this, theapplyform misleads the reader about the author’s intent. -
On modern JavaScript engines, spread is at least as fast as
applyand often faster —applyrequires the engine to wrap and unwrap the arguments array. -
Spread composes cleanly with literal arguments (
fn(a, …rest, b)), whileapplydoes not.
// Bad
Math.max.apply(null, values);
formatter.apply(undefined, parts);
handler.apply(this, args);
Remediation
Replace the call with the spread operator. Calls that pass a real receiver (e.g. fn.apply(other, args)) must be left alone because they depend on apply’s `this-binding semantics.
// Good
Math.max(...values);
formatter(...parts);
handler(...args);
// Still required - explicit this binding
fn.apply(other, args);