Hari 15: Functional Programming — Pure Functions & Immutability
60 min
Last updated 09 Apr 2026
Pure Functions
// Pure function: sama input → sama output, tanpa side effects
const tambah = (a, b) => a + b; // ✅ pure
const kuadrat = x => x * x; // ✅ pure
// Impure: bergantung state luar
let total = 0;
const tambahTotal = x => { total += x; }; // ❌ side effect
// Impure: random
const acak = () => Math.random(); // ❌ tidak deterministik
Immutability
// Jangan mutasi langsung
const arr = [1, 2, 3, 4, 5];
// arr.push(6); // mutasi — hindari
// Buat array baru
const arrBaru = [...arr, 6]; // [1,2,3,4,5,6]
const tanpaIndeks2 = arr.filter((_, i) => i !== 2); // [1,2,4,5]
const updated = arr.map((n, i) => i === 1 ? 99 : n); // [1,99,3,4,5]
// Object immutable
const user = { nama: "Budi", umur: 25 };
const updatedUser = { ...user, umur: 26 }; // bukan mutasi!
Composition
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
const prosesNama = pipe(
s => s.trim(),
s => s.toLowerCase(),
s => s.replace(/\s+/g, "-")
);
console.log(prosesNama(" Belajar JavaScript ")); // "belajar-javascript"
💡
Notice: Chaining .filter().map().sort() adalah functional style — tidak ada mutasi, setiap step return array baru.
Assignment
Buat fungsi transformData yang (1) filter produk dengan harga > 500rb, (2) ambil hanya nama dan harga, (3) urutkan berdasarkan harga ascending. Gunakan metode functional (map/filter/sort tanpa mutasi).
Expected output:
SSD: Rp 800,000
Monitor: Rp 2,500,000
Laptop: Rp 8,500,000
JS
script.js
Solution
Output