JavaScript Basic
In JavaScript, does sort with (a,b) ⇒ b - a produce ascending or descending order? Why?
Answer
(a, b) => b - a sorts the array in descending order (largest to smallest).
How Sort Works
Array.prototype.sort() accepts a comparator compareFn(a, b) that controls ordering:
| Return value | Behavior |
|---|---|
| Negative | a comes before b |
| 0 | Order unchanged |
| Positive | b comes before a |
Analyzing b - a
- If
b > a→ returns positive →bcomes first → larger value first → descending - If
b < a→ returns negative →acomes first → larger value first → descending - If
b === a→ returns 0 → order unchanged
Example
const arr = [3, 1, 4, 1, 5, 9, 2, 6];
// Ascending (a - b)
arr.sort((a, b) => a - b); // [1, 1, 2, 3, 4, 5, 6, 9]
// Descending (b - a)
arr.sort((a, b) => b - a); // [9, 6, 5, 4, 3, 2, 1, 1]
Memory Trick
a - b→ ascending (a goes first)b - a→ descending (b goes first)
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
