JS Built-ins
← Array177 / 226
ArrayArray.prototype.sortbeginner

Array.prototype.sort() β€” alphabetical order

πŸ“– Usage Example
const words = ['banana', 'apple', 'cherry']
words.sort()  // β†’ ['apple', 'banana', 'cherry']

Call sort() without arguments to sort strings in ascending Unicode (alphabetical) order.

Array.prototype.sort()

Array.prototype.sort(compareFn?) sorts elements in place and returns the sorted array. Without a comparator, elements are converted to strings and sorted lexicographically.

⚠️ sort() mutates the original array. Use slice().sort() to sort a copy.

Challenge: Implement sortAlpha(words) that returns a sorted copy without mutating the original.

sortAlpha(['banana', 'apple', 'cherry']) // β†’ ['apple', 'banana', 'cherry']
πŸ’‘ Hints (2)
  • β€’ `slice()` creates a copy so the original array is not mutated.
  • β€’ Default sort is lexicographic β€” useful for strings but wrong for numbers (e.g. `[10, 9]` would sort as `[10, 9]` not `[9, 10]`).