Why does [10, 2, 1].sort() give [1, 10, 2] in JavaScript?
Because sort defaults to string comparison. It converts elements to strings and sorts lexicographically. '10' comes before '2' because '1' < '2'. Use a numeric comparator: sort((a, b) => a - b).
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Common Higher-Order Function Mistakes in JavaScript
Because map returns a new array, which is wasted if you only want side effects. forEach returns undefined and signals that you are not transforming data. Using map for side effects is misleading and wastes memory.
Because without an initial value, reduce uses the first element as the accumulator. An empty array has no first element, so it throws TypeError: Reduce of empty array with no initial value. Always pass an initial value.
Because the arrow function has a block body (braces) with no return statement. Block bodies need an explicit return. Use an expression body (n => n * 2) or add return (n => { return n * 2; }).
Still have questions?
Browse all our FAQs or reach out to our support team
