Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Vue

Arrow Function vs Fungsi Tradisional di JavaScript: Panduan Cepat

1 min read .
Arrow Function vs Fungsi Tradisional di JavaScript: Panduan Cepat

Kadang saya masih bingung milih antara arrow function dan fungsi tradisional di JS, padahal keduanya punya kelebihan masing-masing. Gini deh, mari kita bedah dengan cepat.

1. Ringkasan Cara Definisi Fungsi

  • Deklarasi Fungsi
function greet(name) { return `Hello, ${name}!`; }
  • Ekspresi Fungsi
const greet = function(name) { return `Hello, ${name}!`; };
  • Arrow Function (ES6)
const greet = (name) => `Hello, ${name}!`;

2. Perbedaan Penting

  • Sintaks: Arrow function lebih ringkas. Cocok buat fungsi pendek atau inline.

  • this:

    • Tradisional punya this sendiri.
    • Arrow mewarisi this dari konteks sesayarnya.
function Trad() { this.val=42; setTimeout(function(){ console.log(this.val); },1000); }
function Arrow() { this.val=42; setTimeout(()=>{ console.log(this.val); },1000); }
new Trad();  // undefined
new Arrow(); // 42
  • arguments: Arrow nggak punya.
function trad() { console.log(arguments); }
const arrow = () => console.log(arguments); // error
trad(1,2,3);
arrow(1,2,3);
  • Konstruktor: Arrow nggak bisa dipakai dengan new.

3. Kapan Pakai Mana

Gunakan Arrow Gunakan Tradisional
Fungsi pendek, inline Butuh this sendiri
Pertahankan this leksikal Butuh arguments
Tidak perlu new Perlu sebagai konstruktor

4. Tips Praktis

  • Konsisten dengan gaya kode.
  • Jangan mengorbankan keterbacaan cuma karena arrow lebih pendek.
  • Hati-hati dengan this dan arguments.

Kesimpulan

Pada akhirnya, paham konteks arrow function vs tradisional bikin kode lebih jelas dan aman. Gunakan arrow buat fungsi simpel dan callback, gunakan tradisional saat butuh fleksibilitas this atau konstruktor. Snippet di atas siap dicoba, jadi tinggal eksperimen aja.

Lihat Juga

HTTP Requests di JavaScript dengan Fetch API
HTTP Requests di JavaScript dengan Fetch API
Fetch API itu modern, clean, dan promise-based—solusi yang jauh lebih enak dibanding XMLHttpRequest. Gini deh, contoh CRUD pakai DummyJSON API. 1. Ambil Semua Produk Copy fetch('https://dummyjson.com/products') .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 2. Ambil Produk Berdasarkan ID Copy fetch('https://dummyjson.com/products/1') .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 3. Cari Produk Copy fetch('https://dummyjson.com/products/search?q=phone') .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 4. Tambah Produk Baru Copy fetch('https://dummyjson.com/products/add', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'BMW Pencil' }) }) .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 5. Update Produk Copy fetch('https://dummyjson.com/products/1', { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ title: 'iPhone Galaxy +1' }) }) .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 6. Hapus Produk Copy fetch('https://dummyjson.com/products/1', { method: 'DELETE' }) .then(res => res.json()) .then(console.log) .catch(err => console.error('Error:', err)); 7. Tips & Best Practices Error Handling: selalu pakai .catch() atau try/catch. Async/Await: lebih readable untuk kode kompleks: Copy async function fetchProducts() { try { const res = await fetch('https://dummyjson.com/products'); const data = await res.json(); console.log(data); } catch (err) { console.error('Error:', err); } } fetchProducts(); Keamanan: jangan lupa handle data sensitif dengan aman. Kesimpulan Fetch API bikin HTTP request mudah dan fleksibel di JavaScript. CRUD, searching, dan data manipulation jadi simpel tanpa ribet.
chevron-up