Question:

What will be the output of the following JavaScript code ?
<html> <body> <script> document.write([21, 121, 120, 24, 202].sort()); </script> </body> </html>

Show Hint

To sort numbers in normal ascending numeric order, always pass a comparison function to sort(): myArray.sort((a, b) => a - b); This subtraction-based callback handles numbers correctly instead of using string comparison.
Updated On: Jun 29, 2026
  • 21,121,120,24,202
  • 21,24,120,121,202
  • 120,121,202,21,24
  • 21,121,120,202,24
Show Solution
collegedunia
Verified By Collegedunia

The Correct Option is C

Solution and Explanation



Step 1: Understanding JavaScript's Default Array Sorting Behavior:

A common pitfall in JavaScript is how the Array.prototype.sort() method behaves without parameters. According to ECMAScript specifications, the default sort order is lexicographical (alphabetical/dictionary order). To sort items, JavaScript:
• Temporarily converts every element in the array into a string.
• Compares their UTF-16 character code values sequentially from left to right.

Step 2: String Conversion and Character Comparison:

Let's convert our array $[21, 121, 120, 24, 202]$ into strings: $$\text{Strings: } ["21", "121", "120", "24", "202"]$$ Let's group and compare them character by character:
First Character Comparison:
• Strings starting with character '1': "121", "120".
• Strings starting with character '2': "21", "24", "202". Since character '1' comes before '2' in Unicode/ASCII, all elements starting with '1' are sorted before those starting with '2'.
Sorting strings starting with '1': Compare "120" and "121".
• Index 0: Both have '1'.
• Index 1: Both have '2'.
• Index 2: '0' comes before '1'. Hence, "120" is placed before "121".
Sorting strings starting with '2': Compare "21", "24", and "202".
• Index 0: All have '2'.
• Index 1: Compare character '1' (from "21"), '4' (from "24"), and '0' (from "202").
• In Unicode: '0' comes before '1', which comes before '4'. Therefore, the relative order is: "202" then "21" then "24".

Step 3: Compiling the Final Result:

Combining these parts, the sorted array is: $$[120, 121, 202, 21, 24]$$ When printed using document.write(), JS automatically joins the array elements using commas, yielding the string: $$\texttt{"120,121,202,21,24"}$$ This matches option (C) perfectly.
Was this answer helpful?
0
0