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.
let nums = [40, 1, 5, 200];
nums.sort((a, b) => a - b);
console.log(nums);[1, 5, 40, 200]A comparator function ensures numeric, not alphabetic, sorting.
let colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}red
green
bluefor...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.
