Learn
← Previous Next →

Hari 5: Perulangan — For, While, forEach

55 min Last updated 09 Apr 2026

For Loop

// Classic for
for (let i = 0; i < 5; i++) {
    console.log(`Iterasi ${i}`);
}

// for...of — iterasi nilai array
const buah = ["apel", "mangga", "pisang"];
for (const item of buah) {
    console.log(item);
}

// for...in — iterasi key object
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
    console.log(`${key}: ${obj[key]}`);
}

While & Do-While

let n = 1;
while (n <= 5) {
    process.stdout.write(n + " ");
    n++;
}
// 1 2 3 4 5

Array forEach, map, filter, reduce

const angka = [1, 2, 3, 4, 5];

// forEach — iterasi tanpa return
angka.forEach((n, i) => console.log(`[${i}] = ${n}`));

// map — transformasi (return array baru)
const kuadrat = angka.map(n => n ** 2); // [1, 4, 9, 16, 25]

// filter — saring (return array baru)
const genap = angka.filter(n => n % 2 === 0); // [2, 4]

// reduce — akumulasi ke satu nilai
const total = angka.reduce((acc, n) => acc + n, 0); // 15

💡 Notice: reduce(callback, initialValue) — acc adalah akumulator yang dimulai dari initialValue.

Assignment

Diberikan transaksi = [{id, item, harga}]. Gunakan reduce() untuk hitung total belanja. Gunakan filter() untuk transaksi di atas 100rb. Tampilkan total dan jumlah transaksi mahal.

Expected output:

Total: Rp 11,180,000
Transaksi mahal (>100rb): 3
JS script.js
Solution
Output