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)


 LocalStorage

Set Item

Get Item

Remove Item

Clear All Items

Store Object in LocalStorage


 


 SessionStorage

Set Item

Get Item

Remove Item

Clear All Items

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


 Key Methods Comparison

MethodLocalStorageSessionStorage
setItem(key, value)YesYes
getItem(key)YesYes
removeItem(key)YesYes
clear()YesYes
Data LifetimePermanentTab/session only

 Loop Through Storage Items


 Practical Example: Save Form Data


 


 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

FeatureLocalStorageSessionStorage
LifetimePersistentOnly for current tab
Accessible across tabsYesNo
MethodssetItem, getItem, removeItem, clearSame
Data TypeStrings (use JSON for objects)Strings (use JSON for objects)

You may also like...