Exercise 12: Fetch JSON with Default Value
Problem Statement
Function `fetchJsonSafe(url, defaultValue)` banao jo JSON fetch kare aur fail ho to default return kare.
Example: fetchJsonSafe("https://api.example.com", {})
Sample Output:
await fetchJsonSafe("https://api.example.com", {}) => (JSON or {})
// Returns default on failureSolution
const fetchJsonSafe = async (url, defaultValue = null) => {
try {
const res = await fetch(url);
if (res.ok) return res.json();
} catch {}
return defaultValue;
};Explanation
Overall Goal:
- JSON fetch karna with safe fallback.
Real world:
- Error handling: safe defaults.
- Resilience: fallback values.