69 lines
2.2 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
A sparse array is an array in which the elements do not occupy a contiguous range of indices. In other words, there are gaps (or "holes") between the elements in the array, where some indices have no corresponding value assigned to them.
2021-04-28 16:49:39 +02:00
Including an extra comma in an array literal signifies an empty slot in the array, thus creating a sparse array. An empty slot is not the same as a slot filled with the `undefined` value. In some operations, empty slots behave as if they are filled with `undefined` but are skipped in others.
While this is a well-defined behavior, it can be misleading and raises suspicions about the original intent: an extra comma was intentionally inserted, or perhaps the developer meant to insert the missing value but forgot.
2021-04-28 16:49:39 +02:00
[source,javascript,diff-id=1,diff-type=noncompliant]
2021-04-28 16:49:39 +02:00
----
let a = [1, , 3, 6, 9]; // Noncompliant: Extra comma maybe denoting an oversight
2021-04-28 16:49:39 +02:00
----
You should either remove the extra comma if this was a mistake or add the value you meant to insert initially.
[source,javascript,diff-id=1,diff-type=compliant]
----
let a = [1, 3, 6, 9];
----
Alternatively, if the additional comma was intended, this should be made explicit with an `undefined` element.
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,javascript]
2021-04-28 16:49:39 +02:00
----
let a = [1, undefined, 3, 6, 9];
2021-04-28 16:49:39 +02:00
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#sparse_arrays[Sparse arrays]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Either supply the missing element or remove the extra comma
=== Highlighting
The sparse comma
'''
== Comments And Links
(visible only on this page)
=== on 8 Nov 2017, 09:56:07 Michael Gumowski wrote:
Removing PHP from the list of targeted language. You can not declare sparse arrays in PHP. The following code does not compile:
----
$array = [1, 2, 3, , 4];
----
However, sparse arrays can also be seen as a feature of the language. In the following code, the array is defined with 3 values, but the internal representation of the array is a map, which will use 3 keys: ``++14++``, ``++15++`` and ``++42++``.
----
$array[14] = "hello";
$array[15] = "world";
$array[42] = "yolo";
----
endif::env-github,rspecator-view[]