JavaScript Web Storage

JavaScript Tutorial

JavaScript Web Storage

JavaScript Web Storage allows you to store data locally in the browser.
It is more secure and easier to use than cookies.

Two main types:

  1. LocalStorage – Permanent storage (data persists after closing the browser)

  2. SessionStorage – Temporary storage (data deleted after closing the tab)


1️⃣ LocalStorage

Set Item


Get Item


Remove Item


Clear All Items


Store Object in LocalStorage


 


2️⃣ SessionStorage

Set Item


Get Item

Remove Item


Clear All Items


Data in sessionStorage is deleted automatically when the tab/window is closed.


3️⃣ Key Methods Comparison

Method LocalStorage SessionStorage
setItem(key, value)
getItem(key)
removeItem(key)
clear()
Data Lifetime Permanent Tab/session only

4️⃣ Loop Through Storage Items



5️⃣ Practical Example: Save Form Data


 


6️⃣ Best Practices

  • Use JSON.stringify and JSON.parse for objects/arrays.

  • Avoid storing sensitive info (passwords, tokens) in plain text.

  • Limit data size (LocalStorage usually ~5MB per domain).


Summary Table

Feature LocalStorage SessionStorage
Lifetime Persistent Only for current tab
Accessible across tabs
Methods setItem, getItem, removeItem, clear Same
Data Type Strings (use JSON for objects) Strings (use JSON for objects)

You may also like...