Save a Small Setting Locally
Save a Small Setting Locally
localStorage stores string values for an origin and normally persists across sessions. A school view can save a display preference; explicitly serialize structured data and handle unavailable storage.
Before this topic, review Use Browser Facilities Deliberately if its terms are unfamiliar.
What you’ll learn
- Explain save a small setting locally through the school example.
- Trace the shown operations and distinguish their result from displayed output.
- Make the practice change and explain its consequence: Serialization saves the edited number and parsing restores it before display.
Work through the school example
This is JavaScript in a browser. Read the initial values, then follow each operation to its displayed result. A declaration names a value, a function call performs an operation, and console.log displays its arguments.
JavaScript · browser · complete script for the supplied markup
localStorage.setItem("school-demo", JSON.stringify({ marks: 72 }));
const saved = JSON.parse(localStorage.getItem("school-demo"));
console.log(saved.marks);
localStorage.removeItem("school-demo");
Expected output
72What is Local Storage?
Local Storage is a built-in browser feature that allows developers to store key-value pairs in a web browser, accessible even after the browser is closed and reopened. It is part of the Web Storage API and is useful for persisting user data like theme preferences, tokens, or form inputs.
Key Characteristics of Local Storage
- Data is stored as
stringkey-value pairs. - It is synchronous (blocking operations).
- Data persists even after the browser window is closed.
- Storage size is around 5MB per origin.
Basic Operations with Local Storage
1. Storing Data using localStorage.setItem()
This method allows you to store a key-value pair in local storage.
localStorage.setItem('username', 'john_doe');
The key "username" with value "john_doe" is saved in the browser's local storage.
Question: What happens if we store the same key again?
Answer: It will overwrite the existing value with the new one.
2. Retrieving Data using localStorage.getItem()
Use this method to retrieve the value of a stored key.
const user = localStorage.getItem('username');
console.log(user);
john_doe
3. Removing Data using localStorage.removeItem()
Use this to delete a specific key-value pair.
localStorage.removeItem('username');
The key "username" is removed from local storage.
4. Clearing All Data using localStorage.clear()
This method removes all key-value pairs from local storage.
localStorage.clear();
All keys and values in local storage are deleted.
Storing Complex Data (Objects & Arrays)
Since local storage only stores strings, you need to use JSON.stringify() to store objects or arrays, and JSON.parse() to retrieve them.
Example: Store and Retrieve an Object
const userDetails = {
name: "Alice",
age: 25,
loggedIn: true
};
// Store the object
localStorage.setItem("userDetails", JSON.stringify(userDetails));
// Retrieve the object
const storedData = JSON.parse(localStorage.getItem("userDetails"));
console.log(storedData);
{ name: "Alice", age: 25, loggedIn: true }
Question: What happens if you skip JSON.stringify()?
Answer: The object will be stored as [object Object], which is not useful.
Use Cases of Local Storage
- Remembering theme preferences (dark/light mode)
- Storing authentication tokens
- Saving form inputs temporarily
- Persisting game progress or scores
Best Practices
- Always use
try...catchwithJSON.parse()to avoid errors with corrupted or missing data. - Clean up storage when data is no longer needed.
- Do not store sensitive information (e.g., passwords) in local storage.
Common Mistake to Avoid
Trying to store a number, boolean, or object directly without converting it to a string:
// Mistake
localStorage.setItem("isAdmin", true);
// Correct
localStorage.setItem("isAdmin", JSON.stringify(true));
Summary
Local Storage in JavaScript is a simple yet powerful tool for storing data persistently in the browser. It is ideal for lightweight storage needs that don’t require server communication. Always convert non-string data using JSON.stringify() and handle parsing with JSON.parse() carefully.
Recognize the important boundary
Storage can fail, be cleared or contain invalid old data. Do not store passwords or treat local settings as trusted server records.
Try a small variation
JavaScript · original source for practice
localStorage.setItem("school-demo", JSON.stringify({ marks: 72 }));
const saved = JSON.parse(localStorage.getItem("school-demo"));
console.log(saved.marks);
localStorage.removeItem("school-demo");
Your task: Replace marks:72 with marks:80. Predict the result before running the edited program.
The source is repeated here. If the edit targets the HTML rather than the script, use the markup repeated below; the worked answer also repeats the changed markup.
Worked answer and reasoning
Serialization saves the edited number and parsing restores it before display.
JavaScript · complete worked variation
localStorage.setItem("school-demo", JSON.stringify({ marks: 80 }));
const saved = JSON.parse(localStorage.getItem("school-demo"));
console.log(saved.marks);
localStorage.removeItem("school-demo");
Expected output
80Predict the original program
JavaScript · original program for this question
localStorage.setItem("school-demo", JSON.stringify({ marks: 72 }));
const saved = JSON.parse(localStorage.getItem("school-demo"));
console.log(saved.marks);
localStorage.removeItem("school-demo");
Keep the useful idea
localStorage stores string values for an origin and normally persists across sessions. A school view can save a display preference; explicitly serialize structured data and handle unavailable storage.
Check your variation against this explanation: Serialization saves the edited number and parsing restores it before display.
Use the JavaScript array reference library for individual array operations and boundary tests to check a rule independently.
Reaching the recap and completing the quizzes are separate milestones.