Exercise 3: Remember Last Visited Page

Problem Statement

Create functions `rememberPath(path)` to save and `getRememberedPath()` to load, default "/".

Sample Output:

rememberPath("/products/123")
getRememberedPath() => "/products/123"
getRememberedPath() => "/" (if not set)

Solution

const KEY = 'last_path';
const rememberPath = (p) => localStorage.setItem(KEY, String(p));
const getRememberedPath = () => localStorage.getItem(KEY) || '/';

Explanation

Overall Goal:

  • User ke last visited page ko remember karna.
  • Page reload pe wahi page redirect karna.

Line 1: Constant key

  • const KEY = 'last_path';
  • Storage key constant: typo avoid karne ke liye.
  • Reusable: dono functions me same key use.

Line 2: Save function

  • const rememberPath = (p) => localStorage.setItem(KEY, String(p));
  • p → path string (e.g., "/products/123").
  • String(p) → guarantee karta hai ki string hi store hoga.
  • setItem(KEY, ...) → localStorage me save.

Line 3: Load function

  • const getRememberedPath = () => localStorage.getItem(KEY) || '/';
  • getItem(KEY) → stored path retrieve.
  • || '/' → logical OR:
  • Agar path mila → wahi return.
  • Agar null (not found) → '/' return (home page).

Usage:

  • Page change pe: rememberPath("/products").
  • Page load pe: const path = getRememberedPath() → redirect.

Real world:

  • User experience: last visited page remember.
  • Navigation: back button functionality.
  • Multi-step forms: progress save.