== Why is this an issue?

Many of JavaScript's ``++Array++`` methods return an altered version of the array while leaving the source array intact. ``++reverse++`` and ``++sort++`` do not fall into this category. Instead, they alter the source array _in addition to_ returning the altered version, which is likely not what was intended.


This rule raises an issue when the return values of these methods are assigned, which could lead maintainers to overlook the fact that the original value is altered.


=== Noncompliant code example

[source,javascript]
----
const reversed = a.reverse(); // Noncompliant
const sorted = b.sort(); // Noncompliant
----


=== Compliant solution

[source,javascript]
----
const reversed = [...a].reverse();  // spread the contents of 'a' into a new array, so reverse doesn't impact 'a'
const reversed2 = a.toReversed(); // ES2023 method that copies and reverses the array
a.reverse(); // reverse the array in place

const sorted = [...b].sort(); // spread the contents of 'b' into a new array, so sort doesn't impact 'b'
const sorted2 = b.toSorted(); // ES2023 method that copies and sorts the array
b.sort(); // sort the array in place
----

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Move this array "{0}" operation to a separate statement.


=== Highlighting

``++x.reverse()++``


'''
== Comments And Links
(visible only on this page)

=== on 28 Jul 2017, 14:20:42 Elena Vilchik wrote:
I've put the rule back to Sonar Way as we removed more code-smelly case ``++a = a.reverse();++`` from the scope (moved to RSPEC-1656).   

=== on 16 Jan 2020, 10:23:52 Tibor Blenessy wrote:
Changed to code smell, we can't be sure that the code has a bug, and from issues we find it seems that more often it's not the case

=== on 14 Mar 2021, 11:23:01 JounQin wrote:
Hi, I tried this in SonarJS, it seems `items?.sort()` reports while `items.sort()` does not which is unexpected.


What means this rule is not compatible with `optional chaining`.

=== on 15 Mar 2021, 16:56:59 Tibor Blenessy wrote:
\[~JounQin] I created issue from your report \https://github.com/SonarSource/SonarJS/issues/2513 , however please use our community forum in the future \https://community.sonarsource.com/ ,  this JIRA project should not be used to report specific implementation issues, as it is agnostic about the language.

endif::env-github,rspecator-view[]
