LearnFrenzy
Sign in Take a free test

Array Methods · Find the Error · Question 15

Bug: names are not sorted Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 15 Back to Exercise

The code below runs without an error, but its result is wrong. Which statement correctly identifies the bug?

main.js
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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links