JavaScript Tutorial 9: JSON & LocalStorage

JavaScript Tutorial 9: JSON & LocalStorage

Saving user data directly in the browser across page reloads.

Lesson 8 Review

You have learned how to structure complex data with Arrays and Objects, and how to write clean ES6+ code. But there is a massive problem with JavaScript variables: Memory Loss. The moment a user clicks "Refresh" on your webpage, the browser destroys every single variable you created. To remember a user's shopping cart or theme preference between visits without building a full backend database, we must use the Web Storage API.

Step 1: The Language of the Web (JSON)

To save data, we need to understand JSON (JavaScript Object Notation). JSON is a lightweight format for storing and transporting data. Even though it is named after JavaScript, it is the universal standard used by Python, Java, PHP, and almost every database in existence.

JSON looks almost exactly like a standard JavaScript Object, but with one critical, strict rule: Every single Key and every single String must be wrapped in double quotes " ".

// Normal JavaScript Object
const jsObject = { username: 'Poorna', age: 23 };

// The exact same data, formatted as a raw JSON String
const jsonString = '{ "username": "Poorna", "age": 23 }';

Step 2: Serialization (Stringify and Parse)

The browser's long-term memory (LocalStorage) is dumb. It cannot store complex JavaScript Objects or Arrays. It can only store raw text strings.

[Image of JSON serialization and deserialization process diagram]

Therefore, to save an Object, you must translate it into a JSON string (Serialization). When you pull it back out of memory, you must translate it back into a working JavaScript Object (Deserialization).

  • JSON.stringify(data): Converts a JS Object/Array into a raw text string.
  • JSON.parse(data): Converts a raw JSON text string back into a living JS Object/Array.

The JavaScript: Translating Data

const shoppingCart = [
  { id: 1, item: "Laptop" },
  { id: 2, item: "Mouse" }
];

// 1. We must turn the Array into a String before saving it
const stringifiedCart = JSON.stringify(shoppingCart);
console.log(stringifiedCart); // Outputs: '[{"id":1,"item":"Laptop"},{"id":2,"item":"Mouse"}]'

// 2. Later, when we retrieve the string, we must turn it back into a real Array
const restoredCart = JSON.parse(stringifiedCart);
console.log(restoredCart[0].item); // Outputs: "Laptop"

Step 3: The LocalStorage API

Now that we know how to pack our data into strings, we can actually save it. The localStorage object is built directly into the browser. Data saved here has no expiration date; it will stay on the user's hard drive even if they close the browser and restart their computer.

LocalStorage operates on a simple Key-Value system.

  • localStorage.setItem('keyName', 'valueString'); - Saves data.
  • localStorage.getItem('keyName'); - Retrieves data.
  • localStorage.removeItem('keyName'); - Deletes a specific piece of data.
  • localStorage.clear(); - Wipes the entire database clean.

The JavaScript: Saving to the Hard Drive

// Saving a simple string
localStorage.setItem("themePref", "dark");

// Retrieving it
let currentTheme = localStorage.getItem("themePref");
console.log(currentTheme); // Outputs: "dark"

Step 4: Putting it Together (A Persistent Name Tag)

Let's build a functional, real-world example. We will ask the user for their name, save it, and then display it. If they refresh the page, the JavaScript will check LocalStorage first and automatically welcome them back without asking again.

The HTML & JavaScript:

<!-- HTML -->
<div class="app-box">
  <h2 id="greeting">Welcome, Guest!</h2>
  <input type="text" id="name-input" placeholder="Enter your name">
  <button id="save-btn">Save Name</button>
  <button id="clear-btn">Logout</button>
</div>

/* JavaScript */
const greetingElement = document.querySelector("#greeting");
const inputField = document.querySelector("#name-input");
const saveBtn = document.querySelector("#save-btn");
const clearBtn = document.querySelector("#clear-btn");

/* 1. ON PAGE LOAD: Check if memory exists */
const savedName = localStorage.getItem("userName");
if (savedName !== null) {
  greetingElement.innerText = "Welcome back, " + savedName + "!";
}

/* 2. SAVING DATA: Write to memory */
saveBtn.addEventListener("click", () => {
  let newName = inputField.value;
  localStorage.setItem("userName", newName); // Save to hard drive
  greetingElement.innerText = "Welcome back, " + newName + "!"; // Update UI
});

/* 3. DELETING DATA: Wipe the memory */
clearBtn.addEventListener("click", () => {
  localStorage.removeItem("userName");
  greetingElement.innerText = "Welcome, Guest!";
  inputField.value = "";
});

Final Quiz: Test Your Data Persistence Logic

Click the buttons below to verify your knowledge.

1. What is the fundamental difference between standard JavaScript Variables (`let`, `const`) and LocalStorage?

Post a Comment

0 Comments