Exercise 2: Load JSON from localStorage (safe)
Problem Statement
Create a function `load(key, fallback=null)`. Return fallback for invalid JSON.
Sample Output:
load("theme", "light") => "dark" (if stored)
load("invalid", null) => null
load("user", {}) => {name: "John", age: 30} (if stored)Solution
const load = (key, fallback = null) => {
const raw = localStorage.getItem(key);
if (raw == null) return fallback;
try { return JSON.parse(raw); } catch { return fallback; }
};Explanation
Overall Goal:
- localStorage se data safely load karna.
- Invalid JSON handle karna (error avoid).
- Missing data handle karna (fallback use).
Line 1: Function header
const load = (key, fallback = null) => {key→ storage key.fallback = null→ default value agar data nahi mila.
Line 2: Get raw data
const raw = localStorage.getItem(key);getItem(key)→ key se value retrieve karta hai.- Result: string ya
null(agar key exist nahi karti).
Line 3: Null check
if (raw == null) return fallback;== null→nullyaundefineddono check karta hai.- Agar data nahi hai → fallback return (early exit).
Line 4: Parse JSON
try { return JSON.parse(raw); } catch { return fallback; }try→ JSON parse attempt.JSON.parse(raw)→ string ko JavaScript object me convert.- Agar success → parsed value return.
- Agar fail (invalid JSON) →
catchblock: return fallback→ error case me fallback return.
Example:
load("theme")→"dark"(if stored).load("missing")→null(fallback).load("corrupt")→null(invalid JSON, fallback).
Real world:
- User preferences: settings load karna.
- Cached data: API responses cache se load.
- Form data: draft data restore karna.