🦸‍♀️ JavaScript: map, filter, reduce

🦸‍♀️ JavaScript: map, filter, reduce

The Superpowers of Arrays
(Farewell Ceremony for the For Loop – Eyes Are a Little Watery 🎉)

Once upon a time, JavaScript developers lived like this:

for (let i = 0; i < arr.length; i++) {
  // Whatever God gives…
}

The code was long 📏
Hard to read 👀
Extremely error-prone 💣

Then ES6 arrived…
And JavaScript said:

“Hey buddy, relax…
You don’t need to write a for loop for everything.”

Enter the Array Avengers 🦸‍♂️🦸‍♀️
map, filter, reduce


🗺️ MAP

“EVERYONE STAYS, BUT WITH A SMALL TRANSFORMATION”

🧠 What Does map Do?

  • Takes an array
  • Transforms each element
  • Returns a new array of the same length

map = Transform, don’t remove.

🔹 Basic Example

const numbers = [1, 2, 3, 4];

const squares = numbers.map(n => n * n);

console.log(squares);
// [1, 4, 9, 16]

📌 Step by step:

  • map iterates over the array
  • Takes each number
  • Calculates n * n
  • Pushes results into a new array

⚠️ The original numbers array?
👉 Untouched (map is polite 😌)

😂 Real-Life Analogy

const prices = [100, 200, 300];

const withTax = prices.map(p => p * 1.2);

100 → 120
200 → 240
300 → 360

map: “Everyone gets a 20% raise. Fair is fair.” 💸😅

🧠 When to Use map

  • Preparing API data for the UI
  • Converting numbers to strings
  • Adding new properties to objects

Example: Uppercasing usernames

const users = ["ali", "ayşe", "mehmet"];

const upperUsers = users.map(u => u.toUpperCase());


🧹 FILTER

“REMOVE THE USELESS, KEEP THE QUALITY”

🧠 What Does filter Do?

  • Iterates over the array
  • Keeps elements that match a condition
  • Discards the rest

filter = the selective friend 😎

🔹 Basic Example

const ages = [12, 18, 25, 14, 30];

const adults = ages.filter(age => age >= 18);

console.log(adults);
// [18, 25, 30]

📌 What happened here?

  • Function runs for each age
  • true → stays in the list
  • false → out the door 🚪

😂 Real-Life Analogy

const comments = [
  { spam: true },
  { spam: false },
  { spam: false }
];

const cleanComments = comments.filter(c => !c.spam);

filter: “I have zero tolerance for spam.” ❌📩

🧠 When to Use filter

  • Selecting logged-in users
  • Showing products in stock
  • Separating active vs inactive items

🧮 REDUCE

“COME ON, LET’S TURN ALL OF THIS INTO ONE THING”

🧠 What Does reduce Do?

  • Takes an array
  • Reduces it to a single value

That value can be:

  • a number
  • a string
  • an object
  • an array

reduce = can be anything… slightly dangerous 😈

🔹 Classic Example: Sum

const numbers = [1, 2, 3, 4];

const total = numbers.reduce((acc, n) => {
  return acc + n;
}, 0);

console.log(total);
// 10

📌 Reduce Logic:

  • acc → accumulator (piggy bank 🐷)
  • n → current element
  • 0 → initial value

Steps:

  • 0 + 1 = 1
  • 1 + 2 = 3
  • 3 + 3 = 6
  • 6 + 4 = 10

😵 Why Is Reduce Scary?
Because this is also possible:

const result = arr.reduce((a, b) => {
  return a ? b : a;
});

👆 The one who writes this and the one who reads it both cry.

If you use reduce, prioritize readability.

🧠 When to Use reduce

  • Cart totals
  • Voting results
  • Grouping operations
  • Statistical calculations

🎮 MINI PROJECT: SHOPPING CART

const cart = [
  { product: "Book", price: 100, quantity: 2 },
  { product: "Headphones", price: 300, quantity: 1 },
  { product: "Coffee", price: 50, quantity: 3 }
];

const total = cart.reduce((acc, item) => {
  return acc + item.price * item.quantity;
}, 0);

console.log(total);
// 650

🧠 What did we learn?

  • map → could extract prices
  • filter → could select discounted items
  • reduce → went to checkout 💳

🔗 CHAINING

“ONE ARRAY, THREE SUPERPOWERS”

const result = numbers
  .filter(x => x > 2)
  .map(x => x * 10)
  .reduce((a, b) => a + b, 0);

📌 How to read it:

  • Take numbers greater than 2
  • Multiply them by 10
  • Sum them up

JavaScript says:
“Write readable code, I’ll handle the performance.” 😎


⚠️ MOST COMMON MISTAKES

Using map like filter

arr.map(x => {
  if (x > 5) return x;
});

Result:

[undefined, undefined, 6]

Correct

arr.filter(x => x > 5);

Reduce Show-Off

arr.reduce((a, b) => a + b);

No initial value → surprise 🎁

Safe Reduce

arr.reduce((a, b) => a + b, 0);


🧠 WHICH ONE WHEN? (GOLDEN TABLE)

NeedUse
Transformmap
Selectfilter
Combinereduce

🏁 CONCLUSION

The for loop didn’t die… it just retired 👴

map, filter, reduce:

  • Shorten your code ✂️
  • Increase readability 📖
  • Take you from junior to mid-level 🚀

Writing modern JavaScript means
using the right superpower for the right array 🦸‍♂️

Comments

No comments yet. Why don’t you start the discussion?

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir