Lesson · JavaScript Basics
Arrays and common methods
Arrays preserve order and provide methods for expressing common collection operations.
What you will learn
- Create and index an array
- Transform values with map
- Filter items with a predicate
An ordered collection
An array stores values in order and uses zero-based indexes. Read a value with brackets, add to the end with push, and check length before relying on a position. Arrays can contain objects and other arrays, but consistent item shapes are easier to process.
Transform with map
map calls a function for each item and returns a new array containing the results. It is useful when every item should become a corresponding output, such as turning scores into labels. The original array remains unchanged unless the callback mutates an item it references.
Select with filter
filter returns a new array containing items for which its callback returns a truthy result. The callback should express a simple yes-or-no rule. find is useful when the task needs the first matching item rather than a new collection of all matches.
Choose a method by intent
Use a loop when the task involves several coordinated steps or early exits. Use map, filter, or find when the method name closely describes the operation. Clear intent helps a reader distinguish transformation from selection without tracing every line.
Sort numbers with an explicit comparator
The default sort operation converts values to strings, so a numeric array may not end up in numeric order. Supply a comparison function when sorting numbers, and remember that sort mutates the array. If the original order matters, make a copy before sorting and test the result with a single-digit and a multi-digit value.
const minutes = [10, 25, 40];
const longSessions = minutes.filter((value) => value >= 25);
const labels = longSessions.map((value) => `${value} min`);
console.log(labels.join(', '));
Expected output
25 min, 40 min
Practice exercise
Given an array of scores, create a new array containing only passing scores.
Show a hint
Use filter with a comparison callback.
Show one possible solution
const passing = scores.filter((score) => score >= 40); keeps scores at or above the chosen threshold.
Quick check
find returns the first match; map returns one transformed result per input item.