reverse()
Syntax:
array .reverse()
The reverse() method reverses the order of the array elements, so that the first ele-
ment o f the array becomes the la st and vice versa. The rearrangement of the elements
is done in place, i.e., the elements of the array on which the method is invoked are re-
ordered without creating a new array. The method returns the r eference to the reversed
array, so that the method cha ining is possible.
Example:
var arr = [1, 1, 2, 3, 5, 8];
arr.reverse(); //arr is now [8, 5, 3, 2, 1, 1]
sort()
Syntax:
array .sort()
array .sort(compareFunction )
The sort() meth od sorts the elements of an array, whic h is done in place (i.e., no
copy of the original array is made ), and return s the reference to the sorted array so that
the method chaining is possible. If no additional argument is supplied , then the array
elements are sorted alphabetically (more specifically, in an ascending order according
to the character codes determined by the character encoding).
Because the array elements are sorte d alphabetically, numbers are not arranged as y ou
might expect. For example, 2 comes before 42 in a numeric sort, but since numbers
are converted to strings before sor t is applied, "42" comes before "2".
If you want to use some other criteria to sort elements, then you can supply a custom
compariso n function (compareFunction ). Th is function takes two arguments and
must return one of the following values:
• A value less tha n zero if the first argument should app ear before the second one
in the sorted array.
• A value greater than zero if the second argument should appear before the first
one in the sorted array.
• Zero if both arguments are co nsidered equal in the scope of this sort and their
order doesn’t matter.
If there are any undefined elements, they always come at the end of the sorted array.
This is not possible to change even if you pr ovide your own comparison fu nction
because undefined values are never passed to the compareFunction function.
378 JavaScript Reference