Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
HTML DOM Local Storage clear() method
The HTML DOM Local Storage clear() method removes all key-value pairs from the localStorage object for the current domain. This method provides a quick way to empty the entire local storage without removing items individually.
Syntax
Following is the syntax for the localStorage clear() method −
localStorage.clear()
For sessionStorage, the syntax is −
sessionStorage.clear()
Parameters
The clear() method does not accept any parameters.
Return Value
The method returns undefined and does not provide any return value.
How It Works
When localStorage.clear() is called, it removes all stored data from the localStorage for the current origin (protocol + domain + port). This includes all key-value pairs that were previously stored using setItem(). The operation is synchronous and immediate.
Example − Basic Usage
Following example demonstrates the basic usage of the localStorage clear() method −
<!DOCTYPE html>
<html>
<head>
<title>LocalStorage clear() Method</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px; text-align: center;">
<h2>LocalStorage clear() Demo</h2>
<button onclick="addItems()">Add Sample Data</button>
<button onclick="showItems()">Show Stored Items</button>
<button onclick="clearStorage()">Clear All Data</button>
<div id="output" style="margin-top: 20px; padding: 10px; border: 1px solid #ccc;"></div>
<script>
function addItems() {
localStorage.setItem('username', 'john_doe');
localStorage.setItem('email', 'john@example.com');
localStorage.setItem('theme', 'dark');
document.getElementById('output').innerHTML = 'Sample data added to localStorage!';
}
function showItems() {
let output = '<h3>Current localStorage items:</h3>';
if (localStorage.length === 0) {
output += 'No items in localStorage';
} else {
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
output += `<p><b>${key}:</b> ${value}</p>`;
}
}
document.getElementById('output').innerHTML = output;
}
function clearStorage() {
localStorage.clear();
document.getElementById('output').innerHTML = 'All localStorage data has been cleared!';
}
</script>
</body>
</html>
The output shows buttons to add data, display current items, and clear all stored data −
LocalStorage clear() Demo [Add Sample Data] [Show Stored Items] [Clear All Data] Current localStorage items: username: john_doe email: john@example.com theme: dark (After clicking Clear All Data: "All localStorage data has been cleared!")
Example − Before and After Comparison
Following example shows the localStorage contents before and after calling clear() −
<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Clear Demonstration</title>
<style>
.container { max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif; }
.storage-box { border: 1px solid #ddd; padding: 15px; margin: 10px 0; border-radius: 5px; }
.before { background-color: #e8f5e8; }
.after { background-color: #ffe8e8; }
button { padding: 8px 16px; margin: 5px; cursor: pointer; }
</style>
</head>
<body>
<div class="container">
<h2>LocalStorage clear() Demonstration</h2>
<button onclick="setupData()">Setup Sample Data</button>
<button onclick="clearAndShow()">Clear Storage</button>
<div class="storage-box before">
<h3>Before clear():</h3>
<div id="before-content">Click 'Setup Sample Data' first</div>
</div>
<div class="storage-box after">
<h3>After clear():</h3>
<div id="after-content">Not cleared yet</div>
</div>
</div>
<script>
function setupData() {
// Add multiple items to localStorage
localStorage.setItem('user_id', '12345');
localStorage.setItem('session_token', 'abc123xyz');
localStorage.setItem('preferences', JSON.stringify({theme: 'dark', lang: 'en'}));
localStorage.setItem('last_login', new Date().toISOString());
showBeforeState();
}
function showBeforeState() {
let content = `<p><strong>Total items: ${localStorage.length}</strong></p>`;
for (let i = 0; i < localStorage.length; i++) {
let key = localStorage.key(i);
let value = localStorage.getItem(key);
content += `<p><b>${key}:</b> ${value}</p>`;
}
document.getElementById('before-content').innerHTML = content;
}
function clearAndShow() {
// Show before state
showBeforeState();
// Clear localStorage
localStorage.clear();
// Show after state
let afterContent = `<p><strong>Total items: ${localStorage.length}</strong></p>`;
afterContent += '<p>localStorage is now empty</p>';
document.getElementById('after-content').innerHTML = afterContent;
}
</script>
</body>
</html>
This example clearly shows the localStorage content before and after the clear() operation, demonstrating how all data is removed −
Before clear():
Total items: 4
user_id: 12345
session_token: abc123xyz
preferences: {"theme":"dark","lang":"en"}
last_login: 2024-01-15T10:30:00.000Z
After clear():
Total items: 0
localStorage is now empty
Difference Between clear() and removeItem()
The clear() method removes all items at once, while removeItem() removes only a specific item by its key.
| clear() | removeItem() |
|---|---|
| Removes all key-value pairs from localStorage | Removes only the specified key-value pair |
| No parameters required | Requires the key name as a parameter |
| Faster for clearing multiple items | More selective, preserves other data |
| Cannot be undone easily | Other items remain accessible |
Browser Compatibility
The localStorage.clear() method is supported in all modern browsers including Chrome, Firefox, Safari, Edge, and Internet Explorer 8+. It is part of the Web Storage API specification and has excellent cross-browser compatibility.
Key Points
-
The
clear()method removes all localStorage data for the current domain only -
It does not affect localStorage data from other domains or sessionStorage
-
The operation is synchronous and completes immediately
-
No confirmation dialog is shown to the user
-
Once cleared, the data cannot be recovered unless you have a backup mechanism
Conclusion
The localStorage.clear() method provides a simple and efficient way to remove all stored data from localStorage for the current domain. It is particularly useful for logout functionality, resetting application state, or clearing cached data. Always use this method carefully as the operation is irreversible.
