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 receiver with these arguments", whereas apply reads as "rebind this and call". When the first argument is null / undefined / this, the apply form misleads the reader about the author’s intent.

  • On modern JavaScript engines, spread is at least as fast as apply and often faster — apply requires the engine to wrap and unwrap the arguments array.

  • Spread composes cleanly with literal arguments (fn(a, …​rest, b)), while apply does 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);