]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/prefer-spread.md
0011560c3ce8d22c2a8217a389ef57c38a6bd508
[pve-eslint.git] / eslint / docs / rules / prefer-spread.md
1 # Suggest using spread syntax instead of `.apply()`. (prefer-spread)
2
3 Before ES2015, one must use `Function.prototype.apply()` to call variadic functions.
4
5 ```js
6 var args = [1, 2, 3, 4];
7 Math.max.apply(Math, args);
8 ```
9
10 In ES2015, one can use spread syntax to call variadic functions.
11
12 ```js
13 /*eslint-env es6*/
14
15 var args = [1, 2, 3, 4];
16 Math.max(...args);
17 ```
18
19 ## Rule Details
20
21 This rule is aimed to flag usage of `Function.prototype.apply()` in situations where spread syntax could be used instead.
22
23 ## Examples
24
25 Examples of **incorrect** code for this rule:
26
27 ```js
28 /*eslint prefer-spread: "error"*/
29
30 foo.apply(undefined, args);
31 foo.apply(null, args);
32 obj.foo.apply(obj, args);
33 ```
34
35 Examples of **correct** code for this rule:
36
37 ```js
38 /*eslint prefer-spread: "error"*/
39
40 // Using spread syntax
41 foo(...args);
42 obj.foo(...args);
43
44 // The `this` binding is different.
45 foo.apply(obj, args);
46 obj.foo.apply(null, args);
47 obj.foo.apply(otherObj, args);
48
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]);
54 ```
55
56 Known limitations:
57
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.
59
60 ```js
61 /*eslint prefer-spread: "error"*/
62
63 // This warns.
64 a[i++].foo.apply(a[i++], args);
65
66 // This does not warn.
67 a[++i].foo.apply(a[i], args);
68 ```
69
70 ## When Not To Use It
71
72 This rule should not be used in ES3/5 environments.
73
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.
75
76 ## Related Rules
77
78 * [no-useless-call](no-useless-call.md)