← Back Creator Path 💰 Treasure Tally Lesson 77/20
🎯 Missions
1 Add treasures
2 Sum with reduce()
3 Tally your loot!
🏴‍☠️ 💎 🪙
🏴‍☠️ Treasure Island
Treasure Tally
Ahoy, treasure hunter! You've collected gold coins, gems, and artifacts — but how do you add them ALL UP? Meet .reduce() — the superpower that squishes an entire array into ONE value!

💰 What is .reduce()?

Imagine you have a chest full of coins. You could count them ONE BY ONE... or use .reduce() to add them all up at once!

.reduce() takes every item in an array and squishes them together into ONE value. It's perfect for:

// Sum all numbers in an array
const coins = [10, 25, 5, 50];

const total = coins.reduce((sum, coin) => sum + coin, 0);
// Result: 90

How it works:

sum starts at 0 (the second argument)
• For each item, add it to sum
• After all items, sum is your final answer!

// The magic formula:
array.reduce((accumulator, item) => accumulator + item, startingValue)
✏️ CODE
// 🏴‍☠️ Treasure Tally - Add treasures to your chest! const treasures = [50, 25, 100, 10]; // Use reduce() to sum all treasures: const total = treasures.reduce( (sum, treasure) => sum + treasure, 0 ); console.log("Total treasure: " + total);
✨ RESULT
📦Items: 0
💰Total: 0
Your Treasure Chest
Add treasures below!

🪙 Add Treasures to Chest

Your Total Treasure
0

1Challenge: Count the Gems

Change the treasures array to have different values. What happens when you add more items?

const gems = [25, 50, 25]; const gemTotal = gems.reduce((sum, g) => sum + g, 0); // What is gemTotal? 100 (25 + 50 + 25)

2Challenge: Start from Different Values

The second argument is the STARTING value. What if you start from 100 instead of 0?

const coins = [10, 20, 30]; const total = coins.reduce( (sum, c) => sum + c, 100 // Start from 100! ); // What is total now? 160 (100 + 10 + 20 + 30)

3Challenge: Multiply Instead!

reduce() can do ANY operation! Change + to * to multiply instead of add.

const multipliers = [2, 3, 4]; const product = multipliers.reduce( (result, num) => result * num, 1 ); // 1 × 2 × 3 × 4 = 24

4Challenge: Find the Highest

Can reduce() find the maximum? Use Math.max() inside!

const scores = [45, 89, 23, 67]; const highest = scores.reduce( (max, score) => Math.max(max, score), 0 ); // Find the biggest score: 89

5Master Challenge: Treasure Collection!

Combine filter() and reduce()! First filter treasures over 30, then sum them!

const loot = [10, 50, 25, 75, 15]; const bigLoot = loot.filter(t => t > 25); const sum = bigLoot.reduce((s, t) => s + t, 0); // Only count treasures over 25: 125 (50 + 25 + 75)

🎉 What You Learned