51 lines
1.8 KiB
Plaintext
51 lines
1.8 KiB
Plaintext
== Why is this an issue?
|
|
|
|
``++for...of++`` statements are used to iterate over the values of an iterable object. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol[Iterables] are objects implementing the `@@iterator` method, which returns an object conforming to the https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol[iterator protocol]. JavaScript provides many https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#built-in_iterables[built-in iterables] that can and should be used with this looping statement.
|
|
|
|
The use of the ``++for...of++`` statement is recommended over the `for` statement when iterating through iterable objects as simplifies the syntax and eliminates the need for a counter variable.
|
|
|
|
[source,javascript,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
const arr = [4, 3, 2, 1];
|
|
|
|
for (let i = 0; i < arr.length; i++) { // Noncompliant: arr is an iterable object
|
|
console.log(arr[i]);
|
|
}
|
|
----
|
|
|
|
When looping over an iterable, use the ``++for...of++`` for better readability.
|
|
|
|
[source,javascript,diff-id=1,diff-type=compliant]
|
|
----
|
|
const arr = [4, 3, 2, 1];
|
|
|
|
for (let value of arr) {
|
|
console.log(value);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* MDN web docs - link:++https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of++[``++for...of++``]
|
|
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterator_protocol[Iterator protocol]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Use "for...of" to iterate over this "xxx".
|
|
|
|
|
|
=== Highlighting
|
|
|
|
``++for (...)++``
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|