59 lines
2.3 KiB
Plaintext

== Why is this an issue?
In JavaScript, array indexes should be numeric because arrays are implemented as objects with numeric keys. When an array is created, it is actually an object with properties that are numeric keys. These keys are used to access and assign values stored in the array.
If an array index is not numeric, it will be converted to a string and used as a property name. This can lead to unexpected behavior, as properties are not guaranteed to be ordered in the same way as numeric indexes. For example, if an array has both numeric and non-numeric keys, the non-numeric keys may appear in a different order than the numeric keys.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
let arr = [];
arr[0] = 'a';
arr['name'] = 'bob'; // Noncompliant: The 'name' property with value 'bob' appears after the elements 'a' and 'foo'
arr[1] = 'foo';
----
Using numeric indexes helps maintain consistency and clarity in your code. It follows the common convention of using numbers to represent positions or indices within an ordered sequence. This makes it easier for developers to understand and work with arrays. Furthermore, JavaScript engines can optimize memory allocation and retrieval of array elements in constant time.
[source,javascript,diff-id=1,diff-type=compliant]
----
let arr = [];
arr[0] = 'a';
arr[1] = 'foo';
arr[2] = 'bob';
----
If you really need to use arrays with additional properties, you should wrap the array into another object, add new properties to that object, and preserve the ordered nature of the wrapped array.
[source,javascript]
----
let obj = {
name: 'bob',
arr: ['a', 'foo']
};
----
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array[Array]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#array_indices[Array indices]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object[Object]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make "xxx" an object if it must have named properties; otherwise, use a numeric index here.
=== Highlighting
'name' in ``++foo['name']++``
endif::env-github,rspecator-view[]