Below is the code:

```
<script type="text/javascript">
function sortNumber(a,b) {
return a - b;
}
var n = ["10", "5", "40", "25", "100", "1"];
document.write(n.sort(sortNumber));
</script>
```

Is the `sortNumber`

function for sorting a number? What do a and b mean and why does it exist? Why `sortNumber`

in `n.sort(sortNumber)`

doesn't specify any parameter of `a`

and `b`

?

asked Jan 02 '11 03:01
#### dramasea

The JavaScript `sort()`

function may or may not take a parameter.

The parameter would be a function - meaning `what function is to be used to assess which of two elements should be before the other`

.

The n array is made of strings representing numbers.

Doing a simple `sort()`

without a function, an alphabetical order would be used: the result would be

```
"1", "10", "25"... "5"
```

and is not correct.

Providing a function, `sortNumber`

, tells `sort`

to call that function with two elements of the array each time the `sort`

algorithm wants to know which of the two items is before the other.

Thus `sortNumber`

provided with two items, does a `numerical`

operation to return either

- a negative value, meaning
*a*is before*b* - a positive value,
*b*is before*a* - zero: they're equal in terms of order (order doesn't matter).

answered Sep 19 '22 17:09
#### Déjà vu

You need to consider what `sort()`

consumes; `sort()`

consumes a function that defines the sort oder. To simplify:

```
array.sort(sortfunc)
```

So when you define the function sortNumber, you are actually defining how sort will sort the array.

So if we define a function that's body is defined as:

```
return a - b;
```

We are asking to sort by ascending order

If we define a function with body:

```
return b - a;
```

We are asking to sort by descending order

Hope this helps

answered Sep 19 '22 17:09
#### Adrian Carolli

### Recent Activity

- Apple Pay - authorize.net returns error 153 only when live, sandbox works
- How to continue cursor loop even error occured in the loop
- python find all neighbours of a given node in a list of lists
- Fatal error: Call to a member function setColumn() on a non-object in Magento
- Count how many of each value from a field with MySQL and PHP
- Python 32-bit development on 64-bit Windows [closed]

If you love us? You can donate to us via Paypal or buy me a coffee
so we can maintain and grow! **Thank you!**