Fix the bug: sorting numbers
So far every lesson in this module asked you to write code against types
that catch mistakes before you run anything. Real work is more often the
opposite: someone else's code is already there, it compiles cleanly, and
it's still wrong. The bug below is exactly that kind of bug - number[] is
the right type, TypeScript's checker has nothing to complain about, and the
code runs without throwing. It just returns the wrong array, silently.
The cause is Array.prototype.sort(). Called with no comparator, sort()
converts every element to a string and compares them character by character
so 10 sorts before 9, because "1" sorts before "9". No type
annotation catches this: sorting is a runtime behavior, not a type. The only
way to find the bug is to look at what the function actually returned.
Your task: run the code, look at the returned array, and fix
sortAscending so it returns the numbers in true ascending order.
You'll practice:
Reading actual output instead of trusting that "no error" means "correct"
Fixing JavaScript/TypeScript's default sort() behavior with a numeric comparator
Show a hint
Show solution
Previous Next