0
0
JavascriptHow-ToBeginner · 3 min read

How to Clear localStorage in JavaScript Quickly and Easily

To clear all data stored in localStorage, use the method localStorage.clear(). This removes every key-value pair saved in the browser's localStorage for the current domain.
📐

Syntax

The syntax to clear all data from localStorage is very simple:

  • localStorage.clear(): This method removes all stored items in localStorage for the current website.
javascript
localStorage.clear();
💻

Example

This example shows how to add some data to localStorage, then clear it all using localStorage.clear(). After clearing, the storage will be empty.

javascript
localStorage.setItem('name', 'Alice');
localStorage.setItem('age', '30');
console.log('Before clear:', localStorage.length); // Shows 2
localStorage.clear();
console.log('After clear:', localStorage.length); // Shows 0
Output
Before clear: 2 After clear: 0
⚠️

Common Pitfalls

Some common mistakes when clearing localStorage include:

  • Trying to clear only one item with localStorage.clear() which clears everything, not just one key.
  • Not realizing localStorage.clear() affects all keys for the current domain, which might remove important data unintentionally.
  • Confusing localStorage.clear() with sessionStorage.clear(), which clears session storage instead.
javascript
/* Wrong: Trying to clear one item with clear() */
localStorage.clear(); // This clears all, not just one key

/* Right: To remove one item use removeItem() */
localStorage.removeItem('name');
📊

Quick Reference

Here is a quick summary of localStorage clearing methods:

MethodDescription
localStorage.clear()Removes all key-value pairs from localStorage for the current domain.
localStorage.removeItem(key)Removes a specific item by its key.
localStorage.setItem(key, value)Adds or updates an item in localStorage.
localStorage.getItem(key)Retrieves the value of a specific key.

Key Takeaways

Use localStorage.clear() to remove all stored data for the current website.
localStorage.clear() deletes everything, so use removeItem() to delete specific keys.
Clearing localStorage affects only the current domain's storage.
localStorage and sessionStorage are different; clear() works only on the storage you call it on.
Always check what data you are clearing to avoid losing important information.