⬅ Previous Topic
JavaScript Browser APIsNext Topic ⮕
JavaScript Session Storage⬅ Previous Topic
JavaScript Browser APIsNext Topic ⮕
JavaScript Session StorageLocal 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.
string
key-value pairs.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.
localStorage.getItem()
Use this method to retrieve the value of a stored key.
const user = localStorage.getItem('username');
console.log(user);
john_doe
localStorage.removeItem()
Use this to delete a specific key-value pair.
localStorage.removeItem('username');
The key "username" is removed from local storage.
localStorage.clear()
This method removes all key-value pairs from local storage.
localStorage.clear();
All keys and values in local storage are deleted.
Since local storage only stores strings, you need to use JSON.stringify()
to store objects or arrays, and JSON.parse()
to retrieve them.
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.
try...catch
with JSON.parse()
to avoid errors with corrupted or missing data.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));
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.
⬅ Previous Topic
JavaScript Browser APIsNext Topic ⮕
JavaScript Session StorageYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.