]> git.proxmox.com Git - pve-eslint.git/blob - eslint/docs/rules/no-sparse-arrays.md
first commit
[pve-eslint.git] / eslint / docs / rules / no-sparse-arrays.md
1 # disallow sparse arrays (no-sparse-arrays)
2
3 Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:
4
5 ```js
6 var items = [,,];
7 ```
8
9 While the `items` array in this example has a `length` of 2, there are actually no values in `items[0]` or `items[1]`. The fact that the array literal is valid with only commas inside, coupled with the `length` being set and actual item values not being set, make sparse arrays confusing for many developers. Consider the following:
10
11 ```js
12 var colors = [ "red",, "blue" ];
13 ```
14
15 In this example, the `colors` array has a `length` of 3. But did the developer intend for there to be an empty spot in the middle of the array? Or is it a typo?
16
17 The confusion around sparse arrays defined in this manner is enough that it's recommended to avoid using them unless you are certain that they are useful in your code.
18
19 ## Rule Details
20
21 This rule disallows sparse array literals which have "holes" where commas are not preceded by elements. It does not apply to a trailing comma following the last element.
22
23 Examples of **incorrect** code for this rule:
24
25 ```js
26 /*eslint no-sparse-arrays: "error"*/
27
28 var items = [,];
29 var colors = [ "red",, "blue" ];
30 ```
31
32 Examples of **correct** code for this rule:
33
34 ```js
35 /*eslint no-sparse-arrays: "error"*/
36
37 var items = [];
38 var items = new Array(23);
39
40 // trailing comma (after the last element) is not a problem
41 var colors = [ "red", "blue", ];
42 ```
43
44 ## When Not To Use It
45
46 If you want to use sparse arrays, then it is safe to disable this rule.
47
48 ## Further Reading
49
50 * [Inconsistent array literals](https://www.nczonline.net/blog/2007/09/09/inconsistent-array-literals/)