Introduction
Have you ever visited a website, changed a setting, and found it remembered your preference the next time you came back? That’s the magic of LocalStorage in action.
In this blog post, we’ll explore:
- What is
localStorage
? - When to use it
- How to use it (with examples)
- Limitations
- Real-world use cases
By the end, you’ll be able to use localStorage
to make your websites smarter and more user-friendly.
What is LocalStorage?
localStorage
is a Web API that allows websites to store data on a user’s browser persistently — even after the browser is closed or the computer is restarted.
It’s part of the Web Storage API, which also includes sessionStorage
.
Key Facts:
- Data is saved as key-value pairs (like a dictionary or map)
- Maximum storage size is around 5MB (varies by browser)
- Works only with strings
- Synchronous API (it runs immediately, unlike Promises)
Basic Operations: setItem
, getItem
, removeItem
, clear
Here are the four most used methods of localStorage
:
1. setItem(key, value)
Stores a new key-value pair.
javascriptCopyEditlocalStorage.setItem("username", "codebytex");
2. getItem(key)
Retrieves the value for a given key.
javascriptCopyEditconst name = localStorage.getItem("username");
console.log(name); // Output: "codebytex"
3. removeItem(key)
Deletes a key and its associated value.
javascriptCopyEditlocalStorage.removeItem("username");
4. clear()
Clears all data in localStorage
.
javascriptCopyEditlocalStorage.clear();