JavaScript ยท Chapter 23 of 55

Array Sorting & Iteration

`sort()` reorders array elements in place, but by default it sorts alphabetically (as strings), so numeric sorting needs a comparator function.

For iteration, `forEach()` runs a function once per element without creating a new array, while `for...of` loops offer a simple, readable way to visit each item.

Sorting numbers correctly

`arr.sort((a, b) => a - b)` sorts numbers ascending; `(a, b) => b - a` sorts descending. Without a comparator, sort() treats items as strings.

Iterating

`forEach(fn)` calls fn for every element. `for (const item of arr)` is a clean loop syntax that works on arrays and other iterables.

Example 1 (javascript)
let nums = [40, 1, 5, 200];
nums.sort((a, b) => a - b);
console.log(nums);
Output
[1, 5, 40, 200]

A comparator function ensures numeric, not alphabetic, sorting.

Example 2 (javascript)
let colors = ["red", "green", "blue"];
for (const color of colors) {
  console.log(color);
}
Output
red
green
blue

for...of iterates each element directly.

Key points

  • sort() mutates the array in place and defaults to string sorting.
  • Use `(a, b) => a - b` for ascending numeric sort.
  • forEach() runs a callback for each element but returns undefined.
  • for...of is a clean, modern way to iterate any iterable.
๐Ÿ’ก Note: Without a comparator, sort([10, 1, 2]) surprisingly returns [1, 10, 2] because it compares as strings.

๐Ÿ“ Quick Quiz

1. Default sort() compares elements as:

2. Which comparator sorts numbers ascending?

3. Which loop syntax directly gives you each element?