Disallow Sparse Arrays (no-sparse-arrays)
Sparse arrays contain empty slots, most frequently due to multiple commas being used in an array literal, such as:
var items = [,,];
items array in this example has a
length of 2, there are actually no values in
items. 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:
var colors = [ "red",, "blue" ];
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?
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.
This rule aims to eliminate sparse arrays that are defined by extra commas.
The following patterns are considered warnings:
var items = [,]; var colors = [ "red",, "blue" ];
The following patterns are not warnings:
var items = ; var items = new Array(23); // trailing comma is okay var colors = [ "red", "blue", ];
When Not To Use It
If you want to use sparse arrays, then it is safe to disable this rule.
This rule was introduced in ESLint 0.4.0.