Masukkan Password
91 Perulangan for-in JavaScript
Lecture ini membahas for...in loop. Ini sangat berkaitan dengan lecture sebelumnya tentang for...of, jadi bagian paling penting adalah memahami:
for...in→ mengambil KEY / PROPERTY NAMEfor...of→ mengambil VALUE / ELEMENT
Kalau dua konsep ini sudah jelas, lecture ini sebenarnya cukup sederhana.
1. Mengapa kita membutuhkan for...in?
Sebelumnya kita belajar bahwa object biasa tidak bisa langsung digunakan dengan for...of.
Misalnya:
const product = {
name: "Laptop",
price: 1000,
color: "black"
};
Kalau kita melakukan:
for (const item of product) {
console.log(item);
}
❌ Error.
Karena object biasa bukan iterable.
Sebelumnya kita belajar solusi:
Object.keys(product)
yang menghasilkan Array:
["name", "price", "color"]
Kemudian Array itu baru kita loop:
for (const key of Object.keys(product)) {
console.log(key);
}
Nah, for...in memberikan cara yang lebih langsung:
for (const key in product) {
console.log(key);
}
Tidak perlu membuat Array menggunakan Object.keys() terlebih dahulu. Lecture menjelaskan inilah salah satu alasan for...in berguna untuk object.
2. Apa sebenarnya arti for...in?
Perhatikan:
for (const key in product) {
console.log(key);
}
Baca secara sederhana:
“Untuk setiap key yang ada di dalam
product, jalankan kode berikut.”
Misalnya object:
const product = {
name: "Laptop",
price: 1000,
color: "black"
};
Maka:
product
│
├── name
├── price
└── color
for...in akan mengambil:
name
price
color
Satu per satu.
3. Syntax for...in
Bentuk dasarnya:
for (const variable in object) {
// kode
}
Contoh:
for (const key in product) {
console.log(key);
}
Ada tiga bagian:
for
↓
const key
↓
in
↓
product
for→ kita membuat loopkey→ variable yang menerima property namein→ menandakan kita melakukan iterasi terhadap property/keyproduct→ object yang ingin kita loop
4. Apa isi variable key?
Ini bagian terpenting.
Misalnya:
const product = {
name: "Laptop",
price: 1000,
color: "black"
};
Kemudian:
for (const key in product) {
console.log(key);
}
Pada setiap iterasi:
Iterasi 1
key = "name"
Iterasi 2
key = "price"
Iterasi 3
key = "color"
Jadi output:
name
price
color
Bukan value.
5. for...in pada Object = KEY
Ini kalimat yang sebaiknya kamu hafalkan:
for...inpada object → variable mendapatkan property name/key.
Contoh:
const user = {
name: "John",
age: 28,
gender: "male"
};
for (const key in user) {
console.log(key);
}
Output:
name
age
gender
Visual:
OBJECT
│
┌───────┼────────┐
↓ ↓ ↓
name age gender
↓ ↓ ↓
key key key
6. Lalu bagaimana mendapatkan VALUE?
Nah, sekarang pertanyaannya:
Kalau
keyhanya berisi"name","age","gender", bagaimana kita mendapatkan value-nya?
Caranya menggunakan square bracket notation.
object[key]
Misalnya:
const user = {
name: "John",
age: 28,
gender: "male"
};
for (const key in user) {
console.log(user[key]);
}
Output:
John
28
male
7. Kenapa user[key] bisa bekerja?
Ini sangat penting untuk dipahami.
Misalnya saat iterasi pertama:
key = "name"
Maka:
user[key]
sama saja secara hasil dengan:
user["name"]
Dan:
user["name"]
menghasilkan:
"John"
Iterasi kedua:
key = "age"
Maka:
user[key]
menjadi:
user["age"]
Hasil:
28
Iterasi ketiga:
key = "gender"
Maka:
user[key]
menjadi:
user["gender"]
Hasil:
"male"
Jadi:
for...in
↓
key
↓
user[key]
↓
value
8. Kenapa tidak menggunakan dot notation?
Kamu mungkin berpikir:
user.key
Kenapa tidak?
Karena:
user.key
artinya:
Cari property yang benar-benar bernama
"key".
Padahal kita ingin menggunakan isi variable key.
Misalnya:
let key = "name";
Kita ingin:
user[key]
yang berarti:
user["name"]
Bukan:
user.key
yang berarti:
user["key"]
Ini dua hal yang berbeda.
9. Perhatikan perbedaan ini
Misalnya:
const user = {
name: "John",
age: 28
};
const key = "name";
Dot notation
user.key
Mencari property:
"key"
Hasil:
undefined
Bracket notation
user[key]
Variable key berisi:
"name"
Jadi JavaScript mencari:
user["name"]
Hasil:
"John"
Ini alasan lecture menggunakan:
product[key]
untuk mendapatkan value property.
10. Mendapatkan KEY dan VALUE sekaligus
Sekarang kita bisa melakukan:
const product = {
name: "Laptop",
price: 1000,
color: "black"
};
for (const key in product) {
console.log(key);
console.log(product[key]);
}
Output:
name
Laptop
price
1000
color
black
Atau dibuat lebih bagus:
for (const key in product) {
console.log(
`Property name: ${key}, Property value: ${product[key]}`
);
}
Output:
Property name: name, Property value: Laptop
Property name: price, Property value: 1000
Property name: color, Property value: black
11. Visualisasi lengkap
Misalnya:
const product = {
name: "Laptop",
price: 1000,
color: "black"
};
for...in:
product
│
┌───────────┼───────────┐
↓ ↓ ↓
name price color
↓ ↓ ↓
key key key
│ │ │
↓ ↓ ↓
product[key] product[key] product[key]
↓ ↓ ↓
Laptop 1000 black
Jadi:
key
↓
property name
product[key]
↓
property value
12. Sekarang for...in pada Array
Nah, di sinilah lecture mulai membandingkan for...in dan for...of.
Misalnya:
const colors = [
"red",
"green",
"blue"
];
Kita sebenarnya bisa menggunakan:
for (const index in colors) {
console.log(index);
}
Hasil:
0
1
2
Kenapa?
Karena pada Array, for...in memberikan index.
Jadi:
for...in + Object
→ property name
for...in + Array
→ index
Lecture juga menunjukkan perilaku ini.
13. for...in pada Array bukan value
Misalnya:
const colors = [
"red",
"green",
"blue"
];
for (const index in colors) {
console.log(index);
}
Hasil:
0
1
2
Bukan:
red
green
blue
Karena variable index mendapatkan index.
14. Kalau ingin mendapatkan value dari index?
Gunakan:
colors[index]
Contoh:
for (const index in colors) {
console.log(colors[index]);
}
Output:
red
green
blue
Karena:
Iterasi 1
index = 0
Maka:
colors[index]
menjadi:
colors[0]
→ "red"
Iterasi 2
index = 1
Maka:
colors[1]
→ "green"
Iterasi 3
index = 2
Maka:
colors[2]
→ "blue"
15. Nah, bandingkan dengan for...of
Ini bagian yang wajib benar-benar dikuasai.
Array:
const colors = ["red", "green", "blue"];
for...in
for (const index in colors) {
console.log(index);
}
Hasil:
0
1
2
Variable mendapatkan:
INDEX
for...of
for (const color of colors) {
console.log(color);
}
Hasil:
red
green
blue
Variable mendapatkan:
VALUE
16. Cara mengingat in vs of
Gunakan mnemonic sederhana:
IN → "di dalam apa?" → KEY / INDEX
OF → "value dari apa?" → VALUE
Atau lebih gampang:
for...in
↓
INDEX / KEY
for...of
↓
VALUE
Saya sarankan hafalkan pola ini:
🔑 IN = KEY 📦 OF = VALUE
17. Perbandingan lengkap
Misalnya:
const colors = ["red", "green", "blue"];
| Loop | Variable mendapatkan |
|---|---|
for...in | index |
for...of | value |
forEach() | value + index jika diminta |
traditional for | kita mengontrol index sendiri |
Contoh:
for...in
for (const index in colors) {
console.log(index);
}
→ 0 1 2
for...of
for (const color of colors) {
console.log(color);
}
→ "red" "green" "blue"
forEach
colors.forEach((color, index) => {
console.log(index, color);
});
→ 0 red, 1 green, 2 blue
for
for (let i = 0; i < colors.length; i++) {
console.log(i, colors[i]);
}
→ 0 red, 1 green, 2 blue
18. Kenapa for...in sebaiknya untuk Object?
Ini recommendation yang sangat penting dari lecture.
Secara teknis:
for...in
bisa digunakan untuk Array.
Tetapi:
Jangan menjadikan
for...insebagai pilihan utama untuk looping Array.
Untuk Array lebih baik:
for...of
atau:
forEach()
atau traditional:
for
Sedangkan for...in cocok untuk:
OBJECT
↓
PROPERTY / KEY
Lecture secara eksplisit menyarankan for...in untuk object properties dan for...of untuk iterable seperti Array, String, Map, atau Set.
19. Kenapa for...in kurang cocok untuk Array?
Karena Array sebenarnya adalah struktur data yang dirancang untuk urutan element.
Misalnya:
const colors = ["red", "green", "blue"];
Yang biasanya kita pedulikan:
red
green
blue
bukan:
0
1
2
Kalau memang ingin element:
for (const color of colors) {
console.log(color);
}
lebih natural.
20. Contoh yang relevan dengan CIN/Cinix
Misalnya satu movie:
const movie = {
id: 101,
name: "Bad Boys",
rating: 4.5,
releaseYear: 2024
};
Kita bisa mencetak semua property:
for (const key in movie) {
console.log(key);
}
Output:
id
name
rating
releaseYear
Kalau ingin key + value:
for (const key in movie) {
console.log(`${key}: ${movie[key]}`);
}
Output:
id: 101
name: Bad Boys
rating: 4.5
releaseYear: 2024
Ini sangat cocok untuk object yang strukturnya belum tentu kita tahu sebelumnya.
21. Bandingkan dengan Object.keys()
Sebelumnya:
for (const key of Object.keys(movie)) {
console.log(`${key}: ${movie[key]}`);
}
Dengan for...in:
for (const key in movie) {
console.log(`${key}: ${movie[key]}`);
}
Lebih singkat.
Secara mental:
Cara sebelumnya
Object
↓
Object.keys()
↓
Array of keys
↓
for...of
↓
key
Dengan for...in
Object
↓
for...in
↓
key
Jadi lecture menyebut for...in membuat looping property object lebih mudah.
22. Hubungkan dengan lecture sebelumnya
Sebelumnya kita punya:
Object.keys()
→ ambil KEY
Object.values()
→ ambil VALUE
Object.entries()
→ ambil KEY + VALUE
Sekarang kita punya:
for...in
→ langsung loop KEY
Jadi:
Object.keys(movie)
dan:
for (const key in movie)
sama-sama berhubungan dengan property name, tetapi cara kerjanya berbeda.
23. for...in vs Object.entries()
Misalnya:
const user = {
name: "John",
age: 28
};
Dengan Object.entries():
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}
Dengan for...in:
for (const key in user) {
console.log(key, user[key]);
}
Hasil keduanya bisa sama:
name John
age 28
Perbedaannya:
Object.entries()
→ menghasilkan Array entries dahulu
for...in
→ langsung melakukan iterasi property
24. Hubungkan dengan destructuring
Karena kita sudah belajar destructuring:
const [key, value] = entry;
kita bisa menggunakan:
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}
Sedangkan for...in:
for (const key in user) {
const value = user[key];
console.log(key, value);
}
Jadi keduanya bisa mencapai hasil serupa.
Untuk pemahaman pemula:
for...in
→ lebih langsung untuk property object
Object.entries()
→ berguna kalau kita memang membutuhkan entries sebagai Array
25. Hal yang perlu diperhatikan: for...in mengambil enumerable properties
Ada sedikit detail teknis di balik for...in.
Lecture menyebut enumerable properties.
Untuk level sekarang, kamu cukup memahami:
for...inmelakukan iterasi terhadap property object yang dapat dienumerasi.
Misalnya property biasa yang kita buat:
const user = {
name: "John",
age: 28
};
akan muncul:
name
age
Tidak perlu terlalu memikirkan konsep enumerable dulu. Yang penting kamu tahu istilahnya karena nanti mungkin muncul lagi saat belajar Object yang lebih dalam.
26. Jangan mengira for...in selalu berarti “value”
Ini kesalahan yang sangat sering terjadi.
Lihat:
const product = {
name: "Laptop",
price: 1000
};
for (const item in product) {
console.log(item);
}
Variable item bukan:
Laptop
1000
Tetapi:
name
price
Kalau ingin value:
for (const key in product) {
console.log(product[key]);
}
27. Pola yang harus kamu hafalkan
Untuk Object:
for (const key in object) {
console.log(key);
}
→ mendapatkan key.
Kalau value:
for (const key in object) {
console.log(object[key]);
}
Kalau keduanya:
for (const key in object) {
console.log(key, object[key]);
}
Ini pola yang sangat berguna.
28. Visual super sederhana
Bayangkan object seperti lemari:
PRODUCT
┌─────────────────────┐
│ name → Laptop │
│ price → 1000 │
│ color → Black │
└─────────────────────┘
for...in berjalan melewati label:
name
↓
price
↓
color
Kalau ingin mengambil isi berdasarkan label:
key
↓
product[key]
↓
value
Jadi:
for...in
↓
KEY
↓
object[key]
↓
VALUE
29. Cheat sheet: for...in vs for...of
Ini yang paling penting dari lecture:
for...in | for...of | |
|---|---|---|
| Fokus | Key / index | Value |
| Object | Property name | ❌ Object biasa tidak iterable |
| Array | Index | Element |
| String | Index | Character |
| Umumnya digunakan untuk | Object | Array / iterable |
| Syntax | in | of |
Contoh:
const colors = ["red", "green", "blue"];
for (const x in colors) {
console.log(x);
}
→
0
1
2
Sedangkan:
for (const x of colors) {
console.log(x);
}
→
red
green
blue
30. Hubungan semua loop yang sudah kita pelajari
Sekarang materi looping kita mulai membentuk pola:
LOOPING
│
┌──────────────┼──────────────┐
↓ ↓ ↓
for forEach() for...of
│ │ │
index control value + index value
Dan:
for...in
↓
KEY / PROPERTY
Jadi:
for
→ kontrol manual, terutama index
forEach
→ proses setiap element Array
for...of
→ ambil value satu per satu
for...in
→ ambil key/property object
31. Satu kalimat untuk masing-masing
Kalau nanti kamu lupa, ingat ini:
for
“Saya mau mengontrol index sendiri.”
for (let i = 0; i < arr.length; i++)
forEach
“Saya mau melakukan sesuatu untuk setiap element Array.”
arr.forEach((item, index) => {})
for...of
“Saya mau mengambil value satu per satu.”
for (const item of arr)
for...in
“Saya mau mengambil key/property satu per satu.”
for (const key in obj)
32. Kesimpulan
Lecture ini sebenarnya ingin kamu memahami satu perbedaan utama:
┌─────────────────┐
│ LOOP │
└─────────────────┘
│
┌────────┴────────┐
↓ ↓
for...in for...of
│ │
↓ ↓
KEY / INDEX VALUE
Untuk object:
const movie = {
name: "Bad Boys",
rating: 4.5
};
for (const key in movie) {
console.log(key);
}
→
name
rating
Untuk mendapatkan value:
for (const key in movie) {
console.log(movie[key]);
}
→
Bad Boys
4.5
Sedangkan untuk Array:
const movies = ["A", "B", "C"];
for (const movie of movies) {
console.log(movie);
}
→
A
B
C
Jadi jangan tertukar:
🔑 for...in → KEY / INDEX
📦 for...of → VALUE
Dan untuk penggunaan sehari-hari:
Object →
for...inArray / String / iterable →for...of
Itulah inti dari lecture ini.