🔁 JavaScript Iterables

🔁 JavaScript Iterables

Iterating Over Objects

(“How do I even loop over this thing in JavaScript?” — this one’s for you)


🧠 Let’s Relax First: What Does “Iteration” Mean?

Iteration is actually very simple:

👉 Accessing the elements inside something, one by one

We already do this in real life:

  • 🍕 We eat pizza slice by slice
  • 📺 We watch a series episode by episode
  • 🎧 We listen to a playlist song by song

In JavaScript, some structures say:

“You can walk through me step by step, king 😎”

Those structures are called Iterables.


🤓 What Does Iterable Mean? (Legendary One-Sentence Definition)

An iterable is something you can loop over with for...of.

That’s it.
Anything more is overthinking 😄


✅ Which Structures Are Iterable? (The Golden List)

Structures that are iterable by default in JavaScript:

StructureIterable?
Array
String
Map
Set
arguments
NodeList
Plain Object {}❌ (we’ll fight about this soon)

🎢 Iterating Over an Array (The Easiest One)

const fruits = ["🍎", "🍌", "🍉"];

for (let fruit of fruits) {
  console.log(fruit);
}

🧠 What happened here?

  • for...of → gives you the value itself
  • fruit → one element per loop
  • Output:
🍎
🍌
🍉

📌 Tip:
for...of = “give me the value”
for...in = “give me the key” (coming up)


🔤 Strings Are Iterable Too (Surprise!)

const name = "Cansu";

for (let char of name) {
  console.log(char);
}

🧠 Output:

C
a
n
s
u

💡 Mini fact:
JavaScript can split strings character by character
Works with emojis too 😎


🚨 Big Disappointment: Why Can’t We Iterate Over Objects?

const user = {
  name: "Cansu",
  age: 25
};

for (let item of user) {
  console.log(item);
}

💥 ERROR!

JavaScript says:

“Bro… I have no idea how to walk through this 🤷‍♂️”

Because:

  • Objects don’t have a guaranteed order
  • JavaScript doesn’t know what rule to follow

BUT…
We’re smarter than JavaScript 😏


🛠️ Ways to Iterate Over Objects

(The Life-Saving Trio)


1️⃣ Object.keys() – Loop Over Keys

const user = {
  name: "Cansu",
  age: 25,
  job: "Frontend Dev"
};

const keys = Object.keys(user);

for (let key of keys) {
  console.log(key);
}

🧠 Explanation:

  • Object.keys(user)["name", "age", "job"]
  • Now we have an array
  • Array = iterable 😎

📌 When to use it?
When you only care about the keys.


2️⃣ Object.values() – Loop Over Values

const values = Object.values(user);

for (let value of values) {
  console.log(value);
}

🧠 Output:

Cansu
25
Frontend Dev

📌 When to use it?
When keys don’t matter and you just want the values.


3️⃣ Object.entries() – LEGENDARY MODE 🔥

const entries = Object.entries(user);

for (let [key, value] of entries) {
  console.log(`${key} → ${value}`);
}

🧠 Output:

name → Cansu
age → 25
job → Frontend Dev

📌 Why is this so good?

  • You get both key & value
  • Destructuring ✨
  • Clean, readable, modern

Gives serious senior dev vibes 😎


⚔️ for...in vs for...of (Clearing the Confusion)

for...in

for (let key in user) {
  console.log(key);
}

  • Returns keys
  • Works on objects
  • Risky because of prototype chain 😬

for...of

for (let item of array) {
  console.log(item);
}

  • Returns values
  • Requires iterable
  • Modern & safe ✅

📌 Golden rule:
Object + modern JS = Object.entries() + for...of


🧙‍♂️ The Real Magic: Symbol.iterator

If something is iterable, it has this secret door inside:

Symbol.iterator

When JavaScript sees this, it says:

“Alright, I know how to loop over this.”


🛠️ Let’s Build Our Own Iterable Object (Level Up ⬆️)

const counter = {
  start: 1,
  end: 5,
  [Symbol.iterator]() {
    let current = this.start;
    let last = this.end;

    return {
      next() {
        if (current <= last) {
          return { value: current++, done: false };
        }
        return { done: true };
      }
    };
  }
};

Now let’s use it:

for (let number of counter) {
  console.log(number);
}

🧠 Output:

1
2
3
4
5


🔍 What’s Happening in This Code?

  • [Symbol.iterator]() → requirement for being iterable
  • next() → called on every loop
  • value → current value
  • done: true → “we’re finished” 🚦

📌 Where does this help?

  • Custom data structures
  • Infinite loop control
  • Understanding generators deeply

🎁 BONUS: The Easier Way with Generators

function* counterGen(start, end) {
  for (let i = start; i <= end; i++) {
    yield i;
  }
}

for (let num of counterGen(1, 5)) {
  console.log(num);
}

💡 Shorter
💡 Cleaner
💡 More modern


🧠 Super Tips (Save These ⭐)

  • forEachbreak does not work
  • for...ofbreak & continue do work
  • Want performance? → for...of
  • Iterating objects? → Object.entries()

💬 Closing (From the Heart)

Not everything in JavaScript is iterable…
but those who know how to make things iterable win the game 😌✨

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