1 # Suggest using spread syntax instead of `.apply()`. (prefer-spread)
3 Before ES2015, one must use `Function.prototype.apply()` to call variadic functions.
6 var args = [1, 2, 3, 4];
7 Math.max.apply(Math, args);
10 In ES2015, one can use spread syntax to call variadic functions.
15 var args = [1, 2, 3, 4];
21 This rule is aimed to flag usage of `Function.prototype.apply()` in situations where spread syntax could be used instead.
25 Examples of **incorrect** code for this rule:
28 /*eslint prefer-spread: "error"*/
30 foo.apply(undefined, args);
31 foo.apply(null, args);
32 obj.foo.apply(obj, args);
35 Examples of **correct** code for this rule:
38 /*eslint prefer-spread: "error"*/
40 // Using spread syntax
44 // The `this` binding is different.
46 obj.foo.apply(null, args);
47 obj.foo.apply(otherObj, args);
49 // The argument list is not variadic.
50 // Those are warned by the `no-useless-call` rule.
51 foo.apply(undefined, [1, 2, 3]);
52 foo.apply(null, [1, 2, 3]);
53 obj.foo.apply(obj, [1, 2, 3]);
58 This rule analyzes code statically to check whether or not the `this` argument is changed. So, if the `this` argument is computed in a dynamic expression, this rule cannot detect a violation.
61 /*eslint prefer-spread: "error"*/
64 a[i++].foo.apply(a[i++], args);
66 // This does not warn.
67 a[++i].foo.apply(a[i], args);
72 This rule should not be used in ES3/5 environments.
74 In ES2015 (ES6) or later, if you don't want to be notified about `Function.prototype.apply()` callings, you can safely disable this rule.
78 * [no-useless-call](no-useless-call.md)