1. Local Storage
Have you ever filled out a form, refreshed the page, and the data was still there? That’s Local Storage. It’s a simple key-value store in the browser that persists even if you close the tab.
Limitation: It only stores strings. To store objects, you must use
JSON.stringify().
2. Fetching APIs
An API (Application Programming Interface) is like a waiter. You ask for data (the menu), and it brings it back from the kitchen (the server). We use the fetch() method to do this.
The Code Example
This example shows how to save a user's name locally and how to fetch a random joke from a public API.
// --- PART A: Local Storage ---
// 1. Saving data
localStorage.setItem("theme", "dark");
localStorage.setItem("username", "JS_Master");
// 2. Retrieving data
const savedTheme = localStorage.getItem("theme");
console.log("Current Theme:", savedTheme); // "dark"
// 3. Deleting data
// localStorage.removeItem("theme");
// localStorage.clear(); // Wipes everything
// --- PART B: Fetching an API ---
async function getRandomJoke() {
try {
// Fetching data from a public "Dad Joke" API
const response = await fetch("https://icanhazdadjoke.com/", {
headers: { "Accept": "application/json" }
});
const data = await response.json();
console.log("Here is your joke:");
console.log(data.joke); // Outputs a random joke string
} catch (error) {
console.error("Could not get joke:", error);
}
}
getRandomJoke();