π₯ Callback vs Fallback in JavaScript π₯
Understanding the difference between callbacks and fallbacks is key to writing robust JavaScript code!
1. Callback: Function executed later
β’ Purpose: Handles async tasks (e.g., API requests).
β’ Example: Food delivery app
π¦ Place an order β‘οΈ Get notified when itβs delivered.
function getData(url, callback) {
fetch(url)
.then(response => response.json())
.then(data => callback(data));
}
getData('https://api.example.com/orders', data => console.log(data));
2. Fallback: Default action if something fails
β’ Purpose: Backup plan or default value.
β’ Example: Streaming app
π₯ No HD? Switch to SD automatically.
function getPreferredLanguage(user) {
return user.language || 'en'; // Fallback to 'en'
}
console.log(getPreferredLanguage({ name: 'Alice' })); // 'en'
π‘ Key Difference:
β’ Callback: Executes after a task.
β’ Fallback: Kicks in when something fails.
βοΈ Use both strategically for resilient and user-friendly code!