Web Development Pro | Lesson 024 | Arrays, Loops, and Collection Methods
Web Development Pro · Lesson 24 of 60
Module 3: JavaScript foundations
In this lesson
Prerequisites and learning outcomes
Complete lesson 23 first. This lesson builds on iteration, map, filter, and find. By the end, you can transform workshop records without confusing mutation and returned results. Plan 10–15 minutes for the core explanation and additional time for the worked practice.
Work with a collection instead of repeated variables
The site has several workshop titles. Variables named title1, title2, and title3 are awkward to loop through and expand. An array stores an ordered collection under one name. Each element has a zero-based index: the first title is at index zero, and an array of three titles has length three with its last element at index two.
Arrays can hold many kinds of values, but keeping a clear element contract makes code easier to use. This lesson uses strings for titles and numbers for durations. The next lesson combines related fields into objects. Starting with simple values makes the differences between iteration, transformation, and selection easier to see.
Choose the operation that matches the question
Map creates a new array by transforming each element. Filter creates a new array containing elements that pass a predicate. Find returns the first matching element or undefined. These operations have different result shapes, so choose based on the question rather than treating them as interchangeable loop shortcuts.
const titles = ['Bicycle basics', 'Mending clothes', 'Tool care'];
const durations = [60, 90, 45];
const labels = titles.map(title => title.toUpperCase());
const matching = titles.filter(title => title.toLowerCase().includes('bicycle'));
const firstLong = durations.find(minutes => minutes > 60);
let totalMinutes = 0;
for (const minutes of durations) {
totalMinutes += minutes;
}
console.log(labels.join(' | '));
console.log(matching.join(', '));
console.log(firstLong);
console.log(totalMinutes);
The outputs are uppercase titles joined by separators, Bicycle basics, 90, and 195. The arrow functions supply callbacks to the collection methods. Each callback receives an element and returns the transformation or decision required by that method. The total loop updates a local accumulator once for each duration.
Read callback contracts carefully
The map callback returns the value placed into the new array. If you use a block body and forget return, the resulting positions contain undefined. The filter callback returns a truthy or falsy decision; it does not return a replacement element. Find stops when it finds the first match, which is useful when you need one item rather than a whole matching collection.
An empty filter result is an empty array, which is truthy. To ask whether any matches exist, check matching.length > 0. To handle find, check whether the returned value is undefined under the element contract. If your array legitimately contains undefined values, design a clearer representation rather than relying on an ambiguous result.
Includes on a string performs a case-sensitive substring check. The example normalizes titles to lowercase before searching for lowercase bicycle. That is a simple search strategy for this English demonstration, not a complete international search engine. Accents, locale rules, and tokenization can require more deliberate treatment in a real product.
Know which operations mutate
Map and filter create new arrays rather than changing the original array's structure. Push adds an element to the existing array, while pop removes the last element. Sort traditionally changes the array in place; use a copied array or an appropriate non-mutating alternative when preserving the original order matters. The distinction becomes especially important when several parts of an application share the same collection.
Const prevents replacing the titles binding with a different array, but titles.push('Repair planning') can still modify the array it refers to. This is the binding-versus-content distinction from lesson 21. If a function promises not to modify its input collection, avoid mutating methods or explicitly create the needed copy first.
Copies of arrays containing objects are shallow: the outer array can be new while its elements still refer to the same objects. We will explore that in the next lesson. Do not infer that a new array automatically makes every nested value independent.
Choose a readable loop
For...of iterates over values and is a clear fit for summing durations or processing each title. A traditional indexed for loop is useful when the index itself matters. Be careful with the stopping condition: index < array.length visits valid positions, while <= goes one step beyond the last element.
Do not modify a collection while iterating over it unless you understand the consequences for that specific iteration method. Removing elements can shift later indexes and cause skipped work. Often a filter that produces a new array expresses the intended selection more safely and clearly.
An accumulator should start with the operation's appropriate identity value. A numeric sum starts at zero. A string summary might start as an empty string, though join often expresses that task more directly. Naming totalMinutes instead of total documents the unit and reduces the risk of combining incompatible values.
Test empty and ordinary collections
The supplied tests verify the original titles remain unchanged, the search result is correct, and the duration total is 195. They also check filtering an empty array and finding no match. Empty states are normal in a search interface, so they deserve tests before the DOM renderer is written.
No browser interaction is involved in these tests. They run core JavaScript functions under controlled inputs. Later lessons will connect the returned arrays to real elements and test whether the page communicates zero results clearly rather than showing a blank region.
Worked practice
Worked exercise 1: Fix an index boundary
Task: A loop uses i <= titles.length and prints an extra undefined value. Worked answer: use i < titles.length. With three elements, valid indexes are zero, one, and two. Index three lies just beyond the collection.
Worked exercise 2: Choose map or filter
Task: Produce uppercase versions of every title, then separately select titles containing bicycle. Worked answer: use map for the uppercase transformation and filter for the selection. Filter should not be used merely to transform text because its callback decides inclusion rather than the replacement value.
Worked exercise 3: Detect no results
Task: A search produces [], but if (matches) still enters the success branch. Worked answer: check matches.length > 0. Empty arrays are truthy, so truthiness alone does not mean the collection contains any elements.
Knowledge check
Question 1
What is the last valid index in an array of length three? A) Three. B) Two. C) One. D) Zero, because length counts from zero too.
Check question 1: answer and explanation
Answer: B. Zero-based indexes run from zero through length minus one.
Question 2
Which operation transforms every element into a new result array? A) map. B) find. C) filter. D) forEach.
Check question 2: answer and explanation
Answer: A. Map preserves the collection's positional structure while returning transformed values.
Question 3
What does find return when nothing matches? A) An empty array. B) false necessarily. C) undefined. D) The original array.
Check question 3: answer and explanation
Answer: C. Find returns one matching value or undefined, not a collection of matches.
Question 4
Can push modify an array held by a const binding? A) No, const freezes all contents. B) Only if push returns a new array. C) Only if no other binding refers to that array. D) Yes, the binding stays the same while the array changes.
Check question 4: answer and explanation
Answer: D. Reassignment and mutation are different operations.
Question 5
How should you test whether a result array has items? A) Its length is greater than zero. B) It is strictly unequal to a newly written empty array literal. C) It is truthy. D) Its first element is truthy regardless of the element contract.
Check question 5: answer and explanation
Answer: A. Empty arrays are truthy, so length expresses the actual question.