Local Storage & Session Storage in JavaScript

Local Storage & Session Storage in JavaScript

Local Storage & Session Storage are HTML5's web storage feature that lets you store some information locally on the user's computer, similar to cookies.

The information stored in the web storage isn't sent to the web server.

Web storage allows you to store up to 5MB of data.

Web storage is less secure than cookies.

There are two types of web storage, which differ in scope and lifetime:

  1. Local storage — The local storage uses the localStorage object to store data for your entire website permanently. That means the stored local data will be available on the next day, the next week, or the next year unless you remove it.

    It is synchronous and will block the main thread.

    It is accessible from any window.

  1. Session storage — The session storage uses the sessionStorage object to store data temporarily, for a single browser window or tab. The data disappears when the session ends i.e. when the user closes that browser window or tab.

    It is synchronous and will block the main thread.

    It is accessible from the same window only.

Learn Cookies in detail in this -> blog.

Add data

localStorage.setItem("person1","Bobby");
sessionStorage.setItem("person2","Deadpool");

Read data

localStorage.getItem("person1") // Bobby
sessionStorage.getItem("person2") // Deadpool

Remove data

localStorage.removeItem("person1")
sessionStorage.removeItem("person2")

Clear All Data

localStorage.clear()
sessionStorage.clear()

Cookies vs Local Storage vs Session Storage

CookiesLocal StorageSession Storage
Capacity4kb5MB5MB
BrowsersHTML4/HTML5HTML5HTML5
Accessible fromAny WindowAny WindowSame Tab
ExpiresManually setNeverOn Tab close
Storage LocationBrowser and ServerBrowser onlyBrowser only
Sent with requestsYesNoNo

Final Words

And that’s it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next blog.✌️