Masukkan Password
90 Perulangan for-of JavaScript
Lecture ini membahas for...of loop, yaitu cara modern dan sederhana untuk melakukan perulangan terhadap sesuatu yang iterable, seperti Array dan String. Lecture juga menekankan perbedaan penting antara for...of, for, dan forEach(), terutama soal akses ke index.
1. Apa itu for...of?
Sebelumnya kita sudah belajar beberapa cara melakukan loop:
Traditional for
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
forEach()
colors.forEach((color) => {
console.log(color);
});
Sekarang ada cara lain:
for...of
for (const color of colors) {
console.log(color);
}
Ketiganya bisa digunakan untuk melakukan loop.
Tetapi ada perbedaan besar:
for...offokus pada VALUE/ELEMENT, bukan INDEX.
2. Kenapa namanya for...of?
Perhatikan sintaksnya:
for (const color of colors) {
console.log(color);
}
Ada:
for
↓
const color
↓
of
↓
colors
Artinya kurang lebih:
“Untuk setiap value yang ada di
colors, masukkan value tersebut ke variablecolor.”
Itulah kenapa disebut for…of.
3. Contoh paling sederhana
Misalnya:
const colors = ["red", "green", "blue"];
Kita ingin mencetak semua warna.
Dengan for...of:
for (const color of colors) {
console.log(color);
}
Hasil:
red
green
blue
Yang menarik adalah kita tidak perlu mengurus index secara manual.
Tidak perlu:
let i = 0;
Tidak perlu:
i < colors.length
Tidak perlu:
i++
Dan tidak perlu:
colors[i]
Semua itu ditangani oleh for...of.
4. Bagaimana sebenarnya for...of bekerja?
Mari lihat:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
Secara mental, bayangkan JavaScript melakukan:
Iterasi pertama
color = "red"
Lalu:
console.log(color);
Output:
red
Iterasi kedua
color = "green"
Output:
green
Iterasi ketiga
color = "blue"
Output:
blue
Visual:
colors
│
├── "red" → color → proses
│
├── "green" → color → proses
│
└── "blue" → color → proses
Jadi variable color selalu berisi element yang sedang diproses.
5. for...of tidak perlu tahu berapa kali loop
Ini salah satu kelebihan utamanya.
Misalnya:
const colors = ["red", "green", "blue"];
Ada 3 element → loop 3 kali.
Kalau:
const colors = ["red", "green", "blue", "yellow", "black"];
Ada 5 element → loop 5 kali.
Kalau:
const colors = [];
Tidak ada element → loop 0 kali.
Jadi kita tidak perlu menulis:
colors.length
untuk mengontrol loop.
JavaScript mengikuti iterable tersebut.
6. for...of bisa digunakan untuk Array
Ini penggunaan yang paling umum.
const fruits = ["apple", "banana", "orange"];
for (const fruit of fruits) {
console.log(fruit);
}
Output:
apple
banana
orange
Karena Array adalah iterable.
7. Tapi for...of bukan hanya untuk Array
Ini konsep yang sangat penting.
for...of bekerja pada iterable.
Contohnya:
Iterable
│
├── Array
├── String
├── Map
├── Set
└── iterable lainnya
Lecture menyebut Array, String, Map, Set, dan iterable lainnya. Map dan Set sendiri akan dibahas di bagian berikutnya dalam course.
Untuk sekarang fokus kita:
Array
String
Array of Objects
8. for...of pada String
Ini menarik karena String juga iterable.
Misalnya:
const str = "Hello";
Kita bisa:
for (const char of str) {
console.log(char);
}
Hasil:
H
e
l
l
o
Jadi JavaScript mengambil karakter satu per satu.
Visual:
"Hello"
↓
H → char
e → char
l → char
l → char
o → char
Lecture menggunakan konsep ini untuk membuat fungsi penghitung karakter.
9. Contoh: menghitung jumlah karakter tanpa .length
Lecture memberikan contoh yang bagus.
Misalnya:
const str = "Hello World!";
Kita ingin menghitung jumlah karakter tanpa menggunakan:
str.length
Kita bisa menggunakan for...of.
function countCharacters(value) {
let counter = 0;
for (const char of value) {
counter++;
}
return counter;
}
Kemudian:
console.log(countCharacters(str));
10. Bagaimana fungsi tersebut bekerja?
Misalnya:
"Hello"
Awalnya:
counter = 0
Iterasi 1
char = "H"
counter = 1
Iterasi 2
char = "e"
counter = 2
Iterasi 3
char = "l"
counter = 3
Iterasi 4
char = "l"
counter = 4
Iterasi 5
char = "o"
counter = 5
Loop selesai.
Kemudian:
return counter;
menghasilkan:
5
Lecture menggunakan prinsip yang sama dan mendapatkan jumlah karakter dari string contoh mereka.
11. Kenapa const char boleh digunakan?
Ini mungkin membuat bingung.
Kita menulis:
for (const char of value) {
...
}
Padahal char berubah setiap iterasi.
Bukankah const tidak boleh diubah?
Jawabannya:
Setiap iterasi memiliki binding variable
charuntuk value iterasi tersebut; kita tidak melakukan reassignment terhadapchardalam satu iterasi.
Secara praktis untuk pemula, ingat saja:
for (const item of items) {
...
}
adalah pola yang sangat umum dan aman digunakan kalau kita tidak perlu mengubah variable loop tersebut.
Kalau memang ingin mengubah variable-nya di dalam body, bisa menggunakan let:
for (let item of items) {
...
}
Tetapi biasanya const lebih disukai kalau tidak ada reassignment.
12. for...of pada Array of Objects
Sekarang masuk ke bagian yang sangat relevan dengan project CIN/Cinix kita.
Misalnya:
const products = [
{
name: "Laptop",
price: 1000,
color: "black"
},
{
name: "Phone",
price: 500,
color: "white"
},
{
name: "Tablet",
price: 700,
color: "silver"
}
];
Ini adalah:
Array
│
├── Object
├── Object
└── Object
Kita bisa melakukan:
for (const product of products) {
console.log(product.name);
console.log(product.price);
console.log(product.color);
}
13. Apa isi product pada setiap iterasi?
Ini sangat penting.
Iterasi pertama
product
↓
{
name: "Laptop",
price: 1000,
color: "black"
}
Maka:
product.name
menghasilkan:
"Laptop"
Iterasi kedua
product
↓
{
name: "Phone",
price: 500,
color: "white"
}
Iterasi ketiga
product
↓
{
name: "Tablet",
price: 700,
color: "silver"
}
Jadi:
products Array
↓
for...of
↓
ambil Object satu per satu
↓
product
↓
product.name
product.price
product.color
Lecture juga menggunakan contoh Array yang berisi beberapa product object dan mengambil property name, price, dan color.
14. Ini sangat cocok untuk project CIN/Cinix
Misalnya:
const movies = [
{
id: 1,
name: "bad boys",
rating: 4.5
},
{
id: 2,
name: "the dark knight",
rating: 4.8
}
];
Dengan for...of:
for (const movie of movies) {
console.log(movie.name);
console.log(movie.rating);
}
Hasil:
bad boys
4.5
the dark knight
4.8
Bahkan kita bisa menggunakan function yang sudah kita pelajari:
for (const movie of movies) {
console.log(formatMovieName(movie.name));
console.log(displayStarRatings(movie.rating));
}
Ini membuat kode cukup bersih.
15. Perbedaan for...of dan traditional for
Ini bagian paling penting dari lecture.
Misalnya:
const products = [
"Laptop",
"Phone",
"Tablet"
];
for...of
for (const product of products) {
console.log(product);
}
Kita mendapatkan:
Laptop
Phone
Tablet
Tapi kita tidak langsung mendapatkan index.
Traditional for
for (let i = 0; i < products.length; i++) {
console.log(products[i]);
}
Di sini kita punya:
i = 0
i = 1
i = 2
Jadi kita tahu index.
16. Visual perbedaannya
for...of
products
│
├── "Laptop" → product
├── "Phone" → product
└── "Tablet" → product
Yang kita dapat:
VALUE
Traditional for
products
│
├── index 0 → products[0]
├── index 1 → products[1]
└── index 2 → products[2]
Yang kita punya:
INDEX + VALUE
17. Bagaimana kalau kita membutuhkan index?
Misalnya kita ingin output:
Product 1: Laptop
Product 2: Phone
Product 3: Tablet
for...of saja tidak memberikan index.
Kita bisa menggunakan traditional for:
for (let i = 0; i < products.length; i++) {
console.log(`Product ${i + 1}: ${products[i]}`);
}
Hasil:
Product 1: Laptop
Product 2: Phone
Product 3: Tablet
Lecture menggunakan konsep yang sama: variable i berfungsi sebagai index, lalu products[i] digunakan untuk mengambil object.
18. forEach() juga punya index
Ini perbedaan penting lainnya.
Kita sudah belajar:
products.forEach((product, index) => {
console.log(product);
console.log(index);
});
forEach() callback bisa menerima:
(element, index, array)
Contoh:
products.forEach((product, index) => {
console.log(index, product);
});
Hasil:
0 Laptop
1 Phone
2 Tablet
Jadi:
for...of
→ value
forEach()
→ value + index + array
for
→ index, lalu kita akses value dengan array[index]
Lecture juga menjelaskan bahwa parameter kedua callback forEach() adalah index.
19. Perbandingan tiga jenis loop
Misalnya:
const colors = ["red", "green", "blue"];
Traditional for
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
Kelebihan:
- punya index
- kontrol loop lebih detail
Kekurangan:
- syntax lebih panjang
forEach()
colors.forEach((color, index) => {
console.log(color);
});
Kelebihan:
- sederhana
- punya index
- cocok untuk Array
Kekurangan:
- hanya untuk iterable tertentu melalui method
forEach, bukan semua iterable - kontrol loop seperti
breaktidak seperti traditionalfor
for...of
for (const color of colors) {
console.log(color);
}
Kelebihan:
- syntax sederhana
- langsung mendapatkan value
- bisa digunakan pada berbagai iterable
- tidak perlu mengelola index
Kekurangan:
- tidak menyediakan index secara langsung
20. Kapan sebaiknya menggunakan for...of?
Gunakan for...of ketika kebutuhanmu adalah:
“Saya hanya ingin mengambil setiap value satu per satu.”
Contoh:
for (const movie of movies) {
console.log(movie.name);
}
Kita tidak peduli movie tersebut berada di index berapa.
Ini sangat cocok.
21. Kapan jangan menggunakan for...of?
Kalau kamu membutuhkan index.
Misalnya:
for (const movie of movies) {
// Saya ingin tahu index movie ini
}
for...of tidak memberikan index secara langsung.
Lebih cocok:
for (let i = 0; i < movies.length; i++) {
const movie = movies[i];
console.log(i, movie.name);
}
Atau:
movies.forEach((movie, index) => {
console.log(index, movie.name);
});
Lecture juga menekankan bahwa traditional for lebih cocok ketika membutuhkan index, memodifikasi Array berdasarkan posisi, atau membutuhkan kontrol yang lebih detail atas proses iterasi.
22. for...of vs for...in
Nah, ini sangat penting karena nanti kamu mungkin menemukan for...in.
Jangan tertukar:
for...of
→ VALUE dari iterable
for...in
→ KEY / PROPERTY NAME / INDEX
Contoh Array:
const colors = ["red", "green", "blue"];
for...of
for (const color of colors) {
console.log(color);
}
Output:
red
green
blue
for...in
for (const index in colors) {
console.log(index);
}
Output:
0
1
2
Jadi cara mengingatnya:
OF → value
IN → key/index
Catatan: untuk looping Array, for...of biasanya lebih tepat daripada for...in.
23. Hubungkan dengan lecture sebelumnya tentang Object
Kita sebelumnya belajar bahwa object biasa:
const user = {
name: "John",
age: 28
};
tidak bisa langsung:
for (const item of user) {
...
}
Karena object biasa bukan iterable.
Solusinya:
Object.keys(user)
atau:
Object.values(user)
atau:
Object.entries(user)
Kemudian hasilnya adalah Array/iterable yang bisa kita loop.
Contoh:
for (const key of Object.keys(user)) {
console.log(key);
}
Output:
name
age
Atau:
for (const value of Object.values(user)) {
console.log(value);
}
Output:
John
28
Atau:
for (const [key, value] of Object.entries(user)) {
console.log(key, value);
}
Output:
name John
age 28
Ini menggabungkan lecture sebelumnya + lecture sekarang.
24. Jangan salah memahami “Object tidak bisa di-loop”
Kalimat:
“Object tidak bisa di-loop”
sebenarnya perlu dipahami lebih tepat.
Maksudnya:
Object biasa tidak bisa langsung digunakan sebagai iterable untuk
for...of.
Kita tetap bisa melakukan iterasi terhadap property object menggunakan:
Object.keys()
Object.values()
Object.entries()
Contohnya:
const user = {
name: "John",
age: 28
};
Tidak bisa langsung:
for (const item of user) {}
Tetapi bisa:
for (const key of Object.keys(user)) {}
25. for...of dan break
Salah satu kelebihan for...of adalah kita bisa menggunakan break.
Misalnya:
const colors = ["red", "green", "blue", "yellow"];
for (const color of colors) {
if (color === "blue") {
break;
}
console.log(color);
}
Output:
red
green
Begitu menemukan "blue":
break
↓
stop loop
Ini berbeda dengan forEach(), yang tidak bisa dihentikan dengan break secara langsung.
26. for...of dan continue
Kita juga bisa menggunakan continue.
Misalnya kita ingin melewati "green":
const colors = ["red", "green", "blue"];
for (const color of colors) {
if (color === "green") {
continue;
}
console.log(color);
}
Output:
red
blue
Mental model:
break
→ berhenti total
continue
→ lewati iterasi sekarang
→ lanjut ke iterasi berikutnya
Ini membuat for...of cukup fleksibel.
27. Kesalahan umum pemula
❌ Kesalahan 1: menggunakan of dengan object biasa
const user = {
name: "John",
age: 28
};
for (const value of user) {
console.log(value);
}
❌ Error karena object biasa bukan iterable.
Gunakan:
for (const value of Object.values(user)) {
console.log(value);
}
❌ Kesalahan 2: berharap variable loop adalah index
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
color berisi:
red
green
blue
Bukan:
0
1
2
❌ Kesalahan 3: mengakses colors[color]
Misalnya:
for (const color of colors) {
console.log(colors[color]);
}
Ini salah konsep.
Karena:
color = "red"
sehingga:
colors["red"]
bukan element yang kita inginkan.
Dalam for...of, langsung gunakan:
console.log(color);
28. Hubungan dengan forEach()
Sekarang kita punya tiga cara utama untuk Array:
ARRAY
│
┌──────────┼──────────┐
↓ ↓ ↓
for forEach for...of
│ │ │
index value+index value
Contoh:
for
for (let i = 0; i < movies.length; i++) {
console.log(movies[i]);
}
forEach
movies.forEach((movie, index) => {
console.log(movie, index);
});
for...of
for (const movie of movies) {
console.log(movie);
}
29. Mana yang paling mudah?
Kalau hanya ingin:
“Ambil setiap movie.”
Maka:
for (const movie of movies) {
console.log(movie);
}
sangat mudah dibaca.
Bandingkan:
for (let i = 0; i < movies.length; i++) {
console.log(movies[i]);
}
for...of lebih pendek dan langsung menunjukkan maksud:
untuk setiap movie di movies
30. Mental model paling penting
Bayangkan ada keranjang:
colors
┌──────────────┐
│ red │
│ green │
│ blue │
└──────────────┘
for...of seperti mengambil barang satu per satu:
ambil → red
ambil → green
ambil → blue
Kita tidak peduli barang itu berada di nomor berapa.
Jadi:
for...of
↓
"Berikan saya VALUE satu per satu."
Sedangkan traditional for:
for
↓
"Berikan saya INDEX, nanti saya tentukan
bagaimana mengambil element."
31. Cheat sheet lengkap
| Loop | Mendapat value? | Mendapat index? | Cocok untuk |
|---|---|---|---|
for | ✅ | ✅ | kontrol detail |
forEach() | ✅ | ✅ | Array |
for...of | ✅ | ❌ langsung | iterable |
for...in | ❌ value langsung | ✅ index/key | property/key |
Contoh:
const arr = ["A", "B", "C"];
for
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
}
forEach
arr.forEach((value, index) => {
console.log(index, value);
});
for...of
for (const value of arr) {
console.log(value);
}
for...in
for (const index in arr) {
console.log(index);
}
32. Kesimpulan lecture
Ada 4 hal utama yang perlu kamu bawa dari lecture ini:
① for...of digunakan untuk iterable
Contohnya:
Array
String
Map
Set
② for...of memberikan value
for (const movie of movies) {
console.log(movie);
}
movie = object movie saat ini.
③ for...of tidak memberikan index secara langsung
Kalau butuh index:
for (let i = 0; i < movies.length; i++) {
...
}
atau:
movies.forEach((movie, index) => {
...
});
④ Ingat kalimat ini
for...of= “ambil value satu per satu.”
Array / String / Iterable
↓
for...of
↓
VALUE → proses
Dan kalau kita gabungkan dengan materi sebelumnya:
OBJECT
↓
Object.keys() / values() / entries()
↓
ARRAY
↓
for...of
↓
VALUE
Sedangkan untuk Array langsung:
ARRAY
↓
for...of
↓
ELEMENT / VALUE
Jadi for...of adalah salah satu syntax yang sangat enak untuk membaca data satu per satu tanpa harus sibuk mengurus index.