JavaScript Local Storage

Web storage lets you save small pieces of data in the visitor’s browser. There are two kinds.

StorageLives until
localStorageDeleted by the user or by your code. It stays after closing the browser
sessionStorageThe tab is closed
localStorage.setItem("theme", "dark");

console.log(localStorage.getItem("theme"));
console.log(localStorage.getItem("missing"));

localStorage.removeItem("theme");
console.log(localStorage.getItem("theme"));
Output of the above program is

dark
null
null

  • setItem(key, value) saves.
  • getItem(key) reads, and gives null if there is no such key.
  • removeItem(key) deletes one, clear() deletes everything.

Store objects and arrays

Storage keeps only strings. Convert objects with JSON.

const settings = { theme: "dark", fontSize: 18 };

localStorage.setItem("settings", JSON.stringify(settings));

const saved = JSON.parse(localStorage.getItem("settings"));
console.log(saved.fontSize);
Output of the above program is

18


Example: remember a visitor name

let name = localStorage.getItem("visitorName");

if (!name) {
  name = prompt("What is your name?");
  localStorage.setItem("visitorName", name);
}
console.log("Welcome " + name);
Note: Never save passwords or private data in web storage, because any script on the page can read it. It holds only about 5 MB per site, and the data is not sent to the server (unlike cookies).

Summary

  • localStorage stays, sessionStorage ends with the tab.
  • Use setItem, getItem, removeItem.
  • Use JSON.stringify and JSON.parse for objects.
  • Next: JavaScript Modules.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.