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