What is localStorage in JavaScript?
localStorage is a built-in JavaScript object that allows you to store data in the user's web browser as key-value pairs. The stored data remains available even after the browser is closed and reopened, until it is manually deleted or cleared.
Features of localStorage
- Stores data in the browser.
- Data is saved as string values.
- Data remains available even after refreshing or closing the browser.
- Data is stored only for the same website (same origin).
- No server or database is required.
Syntax
Store Data
localStorage.setItem("key", "value");
Retrieve Data
var value = localStorage.getItem("key");
Remove One Item
localStorage.removeItem("key");
Remove All Items
localStorage.clear();
Example 1: Store Data
<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Example</title>
</head>
<body>
<input type="text" id="txtName" placeholder="Enter Name">
<button onclick="saveData()">Save</button>
<script>
function saveData() {
var name = document.getElementById("txtName").value;
localStorage.setItem("StudentName", name);
alert("Data Saved Successfully");
}
</script>
</body>
</html>
Example 2: Display Stored Data
<!DOCTYPE html>
<html>
<head>
<title>Display Data</title>
</head>
<body>
<h2>Stored Name</h2>
<p id="result"></p>
<script>
var name = localStorage.getItem("StudentName");
document.getElementById("result").innerHTML = name;
</script>
</body>
</html>
Example 3: Remove Data
localStorage.removeItem("StudentName");
Example 4: Clear All Data
localStorage.clear();
Output
Before Saving
Enter Name : Nilesh Gupta
[Save]
After Displaying
Stored Name
Nilesh Gupta
Common localStorage Methods
| Method | Description |
|---|---|
setItem(key, value) | Stores data |
getItem(key) | Retrieves stored data |
removeItem(key) | Removes a specific item |
clear() | Removes all stored data |
key(index) | Returns the key at the given index |
length | Returns the number of stored items |
Advantages
- Easy to use.
- No database or server required.
- Data persists after the browser is closed.
- Useful for user preferences, themes, shopping carts, and small amounts of application data.
Limitations
-
Stores only strings (objects must be converted using
JSON.stringify()andJSON.parse()). - Typical storage limit is around 5–10 MB, depending on the browser.
- Data is not secure—users can view and modify it through the browser's developer tools.
- It should not be used to store sensitive information such as passwords or payment details.
localStorage is commonly used in front-end web applications to save small amounts of data locally without requiring a server or database.
No comments:
Post a Comment