HTML LocalStorage: Persisting Data in the Browser
Discover how to save data directly in the user's browser, creating faster and more personalized web experiences.
/* Your browser's personal storage... */
What is LocalStorage?
The localStorage
API allows you to save key-value pairs in a web browser with no expiration date. This data will persist even after the browser window is closed, making it perfect for saving user preferences, theme settings, or remembering a user's name.
Saving Data: `setItem()`
To save data, use the setItem()
method. It requires two arguments: a unique key (a string) to identify the data, and the value you want to store (also a string). For example: localStorage.setItem('theme', 'dark');
Retrieving Data: `getItem()`
To retrieve data, use the getItem()
method with the key you used to save it. If the key exists, it will return the value as a string. If not, it returns null
. For example: let currentTheme = localStorage.getItem('theme');
Removing Data: `removeItem()` & `clear()`
You can remove a specific item with removeItem(key)
or clear all items saved by your application with clear()
. This gives you full control over the stored data. For example: localStorage.removeItem('theme');
Handling Objects & Arrays with JSON
LocalStorage can only store strings. To save complex data like objects or arrays, you must first convert them to a string using JSON.stringify()
. When you retrieve the data, you must convert it back using JSON.parse()
.
Practice Zone
Interactive Test 1: Match the Methods
Drag the correct localStorage method to its description.
Arrastra en el orden correspondiente.
Arrastra las opciones:
Completa el código:
Interactive Test 2: Complete the Code
Rellena los huecos en cada casilla.
// Save the user's name localStorage.('username', 'Alex'); // Get the user's name let user = localStorage.('username'); // Remove the user's name localStorage.('username');
Practice Example: Code Editor
Save a user's preferred color ('red', 'green', or 'blue') in localStorage and then retrieve it to change the background color of the body.
LocalStorage in Practice
LocalStorage is the secret behind many user-friendly features you see every day. Here are some common use cases.
1. Remembering User Preferences
The most common use is saving settings like a "dark mode" theme. The choice is saved once and then applied every time the user visits.
// On button click:
localStorage.setItem('theme', 'dark');
// On page load:
const theme = localStorage.getItem('theme');
if (theme === 'dark') {
document.body.classList.add('dark');
}
2. Saving Form Progress
For long forms, you can save the input data to localStorage as the user types. If they accidentally close the tab, their progress isn't lost.
const formInput = document.querySelector('#comment');
// Save on input
formInput.addEventListener('input', e => {
localStorage.setItem('commentDraft', e.target.value);
});
// Restore on load
formInput.value = localStorage.getItem('commentDraft') || '';
Important: Never store sensitive information like passwords or personal data in localStorage. It is not secure and can be easily accessed.
LocalStorage Glossary
- localStorage
- A read-only property of the `window` object that allows you to access the Storage object for the document's origin. Data stored here persists across browser sessions.
- setItem(key, value)
- A method that adds a key-value pair to storage, or updates the value if the key already exists. Both key and value must be strings.
- getItem(key)
- Retrieves the value associated with the given key. If the key does not exist, it returns `null`.
- removeItem(key)
- Removes the key-value pair associated with the given key from the storage.
- clear()
- Removes all key-value pairs for the web application's origin from the storage.
- JSON.stringify()
- A method to convert a JavaScript object or array into a JSON string, making it storable in localStorage.
- JSON.parse()
- A method to parse a JSON string, constructing the JavaScript value or object described by the string. Used after retrieving data from localStorage.