Predict Array sort Output
Predict Output Medium
Question
What does this code print?
Code
const nums = [10, 2, 1, 21];
nums.sort();
console.log(nums);
Hint
Default sort converts elements to strings and sorts lexicographically.
Explanation
Without a comparator function, sort() converts elements to strings and sorts them lexicographically (alphabetically). So [10, 2, 1, 21] sorts as strings: "1", "10", "2", "21" — giving [1, 10, 2, 21]. To sort numerically, pass a comparator: nums.sort((a, b) => a - b) gives [1, 2, 10, 21].
Related Resources
Related Lessons
- JavaScript Arrays
Learn about sort.
Related Reference
- JavaScript Array Reference
Reference for sort.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.