Question 15
Back to Exercise
The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?
const names = ["Meera", "Asha", "Ravi"];
names.sort((a, b) => a - b);
console.log(names);
- A Subtracting strings gives NaN, which sort treats like 0 ("equal"), so the order never changes – use a.localeCompare(b) Correct
- B sort cannot sort strings
- C The comparator must return booleans
- D names must be a const
Correct Answer: Option A
"Meera" - "Asha" is NaN. localeCompare returns a proper negative/zero/positive number and sorts them as Asha, Meera, Ravi.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!