Ads by ProfitSence

Explaining Local Storage in JavaScript Code Example

Last Updated on Wednesday 5th Oct 2022

Features of localStorage

  • Shared between all tabs and windows from the same origin.
  • The data does not expire. It remains after the browser restart, and even OS reboots.

Example 1

					localStorage.setItem("test", 1);


Then you can get it like below.

					alert(localStorage.getItem("test")); // 1

  • We only have to be on the same origin; the url path can be different.
  • The local storage is shared between all windows with the same origin.
  • We set the data in one window, and the change becomes visible in another one.

Object way of get/set/remove keys

Example 2

					// set key
localStorage.num = 5;

// get key
alert(localStorage.num); // 5

// remove key
delete localStorage.num;


Looping over keys

  • Storage objects are not iterable.
  • One way is to loop over them as over an array.

Example 3

					for (let i = 0; i < localStorage.length; i++) {
  let key = localStorage.key(i);
  alert(`${key}: ${localStorage.getItem(key)}`);


Example 4

  • We need either to filter fields from the prototype with hasOwnProperty check
					for (let key in localStorage) {
  if (!localStorage.hasOwnProperty(key)) {
    continue; // skip keys like "setItem", "getItem" etc
  alert(`${key}: ${localStorage.getItem(key)}`);

  • Another Way get the "own" keys with Object.keys.
					let keys = Object.keys(localStorage);
for (let key of keys) {
  alert(`${key}: ${localStorage.getItem(key)}`);

  • Note that both key and value must be strings
  • We can use JSON to store objects though
					sessionStorage.user = JSON.stringify({ name: "Adam" });

let user = JSON.parse(sessionStorage.user);
alert(; // Adam