arrow_forward
Sintaks & Perbandingan
code
Fungsi Tradisional
function add(a, b) {
return a + b;
}
const multiply = function(x, y) {
return x * y;
};
return a + b;
}
const multiply = function(x, y) {
return x * y;
};
arrow_forward
Arrow Function
const add = (a, b) => {
return a + b;
}
const multiply = (x, y) => x * y;
// Satu baris tanpa kurung kurawal
return a + b;
}
const multiply = (x, y) => x * y;
// Satu baris tanpa kurung kurawal
Sintaks lebih ringkas - Tidak perlu menulis "function" dan "return" untuk fungsi satu baris
Tidak binding this - Menggunakan this dari lingkup luar, cocok untuk callback
code
Contoh Praktis
// Array methods dengan arrow function
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evenNumbers = numbers.filter(num => num % 2 === 0);
// Event handler
button.addEventListener('click', () => {
console.log('Button clicked!');
});
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(num => num * 2);
const evenNumbers = numbers.filter(num => num % 2 === 0);
// Event handler
button.addEventListener('click', () => {
console.log('Button clicked!');
});
Output:
[2, 4, 6, 8, 10]
[2, 4]
[2, 4, 6, 8, 10]
[2, 4]
lightbulb
Arrow function sangat efisien untuk callback dan functional programming dalam JavaScript modern