intro to localStorage Javascript

Anney Park
3 min readOct 22, 2020

localStorage: maintains a separate storage and it persists even when the browser is closed and reopened.

  • Stores data with no expiration date
  • Gets cleared until overwritten, removed with removeItem, or if the user clears their local data
  • no need for a web server or backend database
  • stores up to 5–10MB of data (depending on the browser)
  • great for getting an idea up and running and for testing purposes

Why use localStorage?

When an app needs to remember something between sessions, you could set up a server which would connect to the internet and have your application store something in the database but sometimes it’s a lot of extra work and you may just want something to keep the data in the browser. This is where localStorage and sessionStorage comes into play. I will specifically cover localStorage in this blog post.

Simple example of how localStorage works in your console. Open your browser console by opening Dev Tools in Chrome and clicking on the Console tab:

localStorage.setItem('username', 'anney');
let value = localStorage.getItem('username');
console.log(value);

You can view your stored data in your browser’s console (mac: CMD + option + J or Windows/Linux: Ctrl + Shift + J ) under the Application tab.

The stored data persists even when the browser is closed and reopened. It will stick around until it is overwritten, removed with removeItem, or if the user clears their local data.

These are the methods for local storage:

  • localStorage.setItem() — when passed a key name and value, will add that key to the storage, or update that key’s value if it already exists.
  • localStorage.getItem() — when passed a key name, will return that key’s value
  • localStorage.removeItem() — when passed a key name, will remove that key from the storage
  • localStorage.key() — when passed a number n, this method will return the name of the nth key in the storage
  • localStorage.clear() — clear storage

Pos & Cons when using localStorage

Source: https://getrevising.co.uk/grids/local_storage

Possible Issue with localStorage that leads to sessionStorage usage

It is possible that a hacker can retrieve all the data you’ve stored in local storage so anything sensitive you have like a user’s session data can be compromised. This is where sessionStorage might be a better choice. I will not dive into sessionStorage in depth but sessionStorage is a better choice over localStorage because stored data is cleared when the browser tab is closed. This is important because if a hacker can get a copy of your JSON Web Token or JWT (compact URL-safe means of representing claims to be transferred between two parties) then they can make requests on your behalf.

--

--