JS enginesavedvisitslocalhost:8000/visits.htmlHello!1<p id="msg">Hello!</p>2<script src="visits.js"></script>1const saved = localStorage.getItem("visits");2const visits = Number(saved) + 1;3localStorage.setItem("visits", visits);4const msg = document.querySelector("#msg");5msg.textContent = "Visit number " + visits;localStoragelocalhost:8000keyvaluevisits(empty)null1"1"2"2"
Back: the browser (its JavaScript engine, the page's memory, and the window showing the page)Front: the two files, visits.html and visits.js, and localStorageTokens: the script, instructions, the key and the values null, 1, "1", 2 and "2"At the back, the browser's JavaScript engine and the page's memory (saved and visits), and the browser window showing visits.html. In front, the two files as cards and localStorage. On the first visit getItem returns null, so visits is 1 and setItem stores the string "1". A reload empties the page's memory but not localStorage, so the second visit reads "1", turns it into a number and stores "2". Web storage is small: browsers allow about 5 MiB of localStorage per origin. It is also synchronous, so every getItem and setItem waits for the browser. Use it for small settings, not large data.

Memory and storage

  1. A page's variables live in memory and vanish when the page closes or reloads. Web storage keeps small pieces of text in the browser itself. localStorage holds key-value pairs for each website and survives reloads and restarts.

The first visit

Reload and come back

The rules

What happens

// step 1/11 · storage
memory         variables: gone on reload
localStorage   key-value pairs, all strings
               one store per origin
               kept after reloads and restarts
sessionStorage the same, cleared when the tab closes

The Web Storage API keeps every key and value as a string. setItem converts what you pass to a string, so the number 1 is stored as "1", and an object would be stored as the useless text "[object Object]" unless you JSON.stringify it first. The memory boxes are a simplification: saved and visits are bindings in the script's scope. When the page is reloaded, a fresh script runs with fresh bindings; nothing from the old page's memory survives.