]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/src/rules/prefer-spread.md
import 8.23.1 source
[pve-eslint.git] / eslint / docs / src / rules / prefer-spread.md
1 ---
2 title: prefer-spread
3 layout: doc
4 rule_type: suggestion
5 related_rules:
6 - no-useless-call
7 ---
8
9
10 Before ES2015, one must use `Function.prototype.apply()` to call variadic functions.
11
12 ```js
13 var args = [1, 2, 3, 4];
14 Math.max.apply(Math, args);
15 ```
16
17 In ES2015, one can use spread syntax to call variadic functions.
18
19 ```js
20 /*eslint-env es6*/
21
22 var args = [1, 2, 3, 4];
23 Math.max(...args);
24 ```
25
26 ## Rule Details
27
28 This rule is aimed to flag usage of `Function.prototype.apply()` in situations where spread syntax could be used instead.
29
30 ## Examples
31
32 Examples of **incorrect** code for this rule:
33
34 ::: incorrect
35
36 ```js
37 /*eslint prefer-spread: "error"*/
38
39 foo.apply(undefined, args);
40 foo.apply(null, args);
41 obj.foo.apply(obj, args);
42 ```
43
44 :::
45
46 Examples of **correct** code for this rule:
47
48 ::: correct
49
50 ```js
51 /*eslint prefer-spread: "error"*/
52
53 // Using spread syntax
54 foo(...args);
55 obj.foo(...args);
56
57 // The `this` binding is different.
58 foo.apply(obj, args);
59 obj.foo.apply(null, args);
60 obj.foo.apply(otherObj, args);
61
62 // The argument list is not variadic.
63 // Those are warned by the `no-useless-call` rule.
64 foo.apply(undefined, [1, 2, 3]);
65 foo.apply(null, [1, 2, 3]);
66 obj.foo.apply(obj, [1, 2, 3]);
67 ```
68
69 :::
70
71 Known limitations:
72
73 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.
74
75 ```js
76 /*eslint prefer-spread: "error"*/
77
78 // This warns.
79 a[i++].foo.apply(a[i++], args);
80
81 // This does not warn.
82 a[++i].foo.apply(a[i], args);
83 ```
84
85 ## When Not To Use It
86
87 This rule should not be used in ES3/5 environments.
88
89 In ES2015 (ES6) or later, if you don't want to be notified about `Function.prototype.apply()` callings, you can safely disable this rule.