In Jurassic Park, every morning the team goes through the entire list of dinosaurs - checking health, assigning feedings, creating reports. JavaScript has specialized methods for iterating through arrays: each with a specific purpose and use case.
forEach executes a function for every element. It doesn't return anything (returns
undefined):1const dinosaurs = ['Rex', 'Blue', 'Delta', 'Echo', 'Charlie'];
2
3// Basic forEach
4dinosaurs.forEach(function(dino, index, array) {
5 console.log(`${index + 1}. ${dino}`);
6});
7
8// Arrow function - more concise
9dinosaurs.forEach((dino, i) => console.log(`${i + 1}. ${dino}`));
10
11// With object array
12const dinoData = [
13 { name: 'Rex', zone: 'A' },
14 { name: 'Blue', zone: 'B' }
15];
16
17dinoData.forEach(({ name, zone }) => {
18 console.log(`${name} is in zone ${zone}`);
19});map creates a new array by transforming each element. Original array is unchanged:
1const dinos = [
2 { name: 'Rex', weight: 8000, dangerous: true },
3 { name: 'Blue', weight: 15, dangerous: true },
4 { name: 'Stego', weight: 3500, dangerous: false }
5];
6
7// Extract just names
8const names = dinos.map(d => d.name);
9// ['Rex', 'Blue', 'Stego']
10
11// Transform objects
12const reports = dinos.map(d => ({
13 id: d.name.toUpperCase(),
14 weightTons: (d.weight / 1000).toFixed(1),
15 status: d.dangerous ? 'DANGER' : 'SAFE'
16}));
17// [{id: 'REX', weightTons: '8.0', status: 'DANGER'}, ...]
18
19// Transform strings
20const codes = ['alpha', 'bravo', 'charlie'];
21const upperCodes = codes.map(c => c.toUpperCase());
22// ['ALPHA', 'BRAVO', 'CHARLIE']filter creates a new array with only elements that pass the test:
1const dinos = [
2 { name: 'Rex', weight: 8000, dangerous: true, health: 95 },
3 { name: 'Blue', weight: 15, dangerous: true, health: 100 },
4 { name: 'Stego', weight: 3500, dangerous: false, health: 70 },
5 { name: 'Brachi', weight: 25000, dangerous: false, health: 85 }
6];
7
8// Only dangerous
9const dangerous = dinos.filter(d => d.dangerous);
10// [Rex, Blue]
11
12// Only healthy (> 80)
13const healthy = dinos.filter(d => d.health > 80);
14// [Rex, Blue, Brachi]
15
16// Multiple conditions
17const dangerousAndHealthy = dinos.filter(d => d.dangerous && d.health > 80);
18// [Rex, Blue]
19
20// Filter strings
21const zones = ['A', 'B1', 'C', 'B2', 'D'];
22const bZones = zones.filter(z => z.startsWith('B'));
23// ['B1', 'B2']reduce is the most powerful iteration method - it can aggregate the entire array into a single value:
1const dinos = [
2 { name: 'Rex', weight: 8000, dailyFood: 200 },
3 { name: 'Blue', weight: 15, dailyFood: 5 },
4 { name: 'Stego', weight: 3500, dailyFood: 50 },
5 { name: 'Brachi', weight: 25000, dailyFood: 300 }
6];
7
8// Sum of all weights
9const totalWeight = dinos.reduce((sum, d) => sum + d.weight, 0);
10// 36515
11
12// Sum of daily food
13const totalFood = dinos.reduce((sum, d) => sum + d.dailyFood, 0);
14// 555
15
16// Find heaviest
17const heaviest = dinos.reduce((max, d) => d.weight > max.weight ? d : max, dinos[0]);
18// { name: 'Brachi', weight: 25000, ... }
19
20// Build object from array (grouping)
21const byDanger = dinos.reduce((groups, d) => {
22 const key = d.dangerous ? 'dangerous' : 'safe';
23 if (!groups[key]) groups[key] = [];
24 groups[key].push(d.name);
25 return groups;
26}, {});
27// { safe: ['Stego', 'Brachi'] }
28// (no dangerous property in our example data since we removed it above)1const dinos = [
2 { name: 'Rex', health: 95, zone: 'A' },
3 { name: 'Blue', health: 40, zone: 'B' },
4 { name: 'Stego', health: 80, zone: 'A' }
5];
6
7// find - returns first matching element
8const sick = dinos.find(d => d.health < 50);
9console.log(sick); // { name: 'Blue', health: 40, zone: 'B' }
10
11// findIndex - returns index of first match
12const sickIndex = dinos.findIndex(d => d.health < 50);
13console.log(sickIndex); // 1
14
15// When not found
16const missing = dinos.find(d => d.zone === 'C');
17console.log(missing); // undefined
18
19const missingIndex = dinos.findIndex(d => d.zone === 'C');
20console.log(missingIndex); // -11const dinos = [
2 { name: 'Rex', health: 95, dangerous: true },
3 { name: 'Blue', health: 40, dangerous: true },
4 { name: 'Stego', health: 80, dangerous: false }
5];
6
7// some - at least one matches (short-circuits!)
8const anySick = dinos.some(d => d.health < 50);
9console.log(anySick); // true (Blue has 40)
10
11const anyDangerous = dinos.some(d => d.dangerous);
12console.log(anyDangerous); // true
13
14// every - all match (short-circuits!)
15const allHealthy = dinos.every(d => d.health > 50);
16console.log(allHealthy); // false (Blue has 40)
17
18const anyDino = dinos.every(d => d.name !== '');
19console.log(anyDino); // trueThe real power of array methods is chaining them together:
1const parkData = [
2 { name: 'Rex', zone: 'A', health: 95, weight: 8000, dangerous: true },
3 { name: 'Blue', zone: 'B', health: 40, weight: 15, dangerous: true },
4 { name: 'Stego', zone: 'A', health: 80, weight: 3500, dangerous: false },
5 { name: 'Brachi', zone: 'C', health: 90, weight: 25000, dangerous: false },
6 { name: 'Echo', zone: 'B', health: 30, weight: 12, dangerous: true }
7];
8
9// Find all dangerous dinosaurs in zone B that need health check (health < 50)
10// Return their names sorted alphabetically
11const criticalReport = parkData
12 .filter(d => d.dangerous && d.zone === 'B') // dangerous and in zone B
13 .filter(d => d.health < 50) // health below 50
14 .sort((a, b) => a.health - b.health) // sort by health ascending
15 .map(d => `${d.name} (health: ${d.health})`); // format output
16
17console.log(criticalReport);
18// ["Echo (health: 30)", "Blue (health: 40)"]
19
20// Total weight of all zone A dinosaurs
21const zoneAWeight = parkData
22 .filter(d => d.zone === 'A')
23 .reduce((sum, d) => sum + d.weight, 0);
24
25console.log(`Zone A total weight: ${zoneAWeight}kg`); // 11500kg"Iteration methods are like the park's morning briefing" - says Dr. Rex. "forEach for going through the daily checklist, filter for selecting only those who need attention, map for creating reports, reduce for computing totals. Each tool has its purpose!"