Exercises
Spot the bug
Each sample reply below was written for this lesson. Try to find the mistake, then read the MDN note that explains it.
Array.prototype.sort() sorts an array in place. The default order is ascending, built by converting the elements to strings and then comparing their UTF-16 code unit values. MDN: Array.sort() MDN's own example shows that [1, 30, 4, 21, 100000].sort(), with no compare function, comes out as [1, 100000, 21, 30, 4], not numeric order. MDN: Array.sort()
In a numeric sort, 9 comes before 80, but because numbers are converted to strings, "80" comes before "9" in the Unicode order. MDN: Array.sort()
What is wrong with this reply?
The assistant says scores.sort() will print the scores from smallest to largest. What is the actual problem?
Which line holds the bug?
Tap the line you would change first.
To sort numbers in ascending order, MDN's memory aid is the compare function (a, b) => a - b. A compareNumbers helper that returns a - b does the same. MDN: Array.sort() Because sort() changes the original array, use toSorted() if you want a new sorted array and to leave the original alone. MDN: Array.sort()
A common confusion: ["1", "2", "3"].map(parseInt) does not give [1, 2, 3]. The actual result is [1, NaN, NaN]. MDN: Array.map() parseInt takes two arguments, the string and a radix. Array.map passes three arguments (the element, the index and the array), so the index is wrongly used as the radix. parseInt("2", 1) and parseInt("3", 2) are both NaN. MDN: Array.map()
What does this code actually produce?
The assistant says ["1", "2", "3"].map(parseInt) turns the strings into the numbers [1, 2, 3]. What is the actual result, according to MDN?
The fix is to pass a function that takes one argument and sets the radix yourself, for example (str) => parseInt(str, 10), which gives [1, 2, 3]. MDN: Array.map()
Sample assistant replies
The "assistant" replies on this site were written by us for the lesson. They are not live results from an AI tool, and nothing you type is sent to one. That way every visitor sees the same lesson.
A score appears once you have tried each checker on this page.