AI Code

JavaScript Web Storage


  • localStorage.setItem(name, value);

  • localStorage.getItem(name);

  • = value;


  • localStorage.clear()

  • localStorage.removeItem(name);


nameThe key/name of the item
valueThe value of the item


Using localStorage

The localStorage object provides persistent (but not permanent - see limits below) key-value storage of strings. Any changes are immediately visible in all other windows/frames from the same origin. The stored values persistent indefinitely unless the user clears saved data or configures an expiration limit. localStorage uses a map-like interface for getting and setting values.

localStorage.setItem('name', "John Smith");
console.log(localStorage.getItem('name')); // "John Smith"

console.log(localStorage.getItem('name')); // null

If you want to store simple structured data, you can use JSON to serialize it to and from strings for storage.

var players = [{name: "Tyler", score: 22}, {name: "Ryan", score: 41}];
localStorage.setItem('players', JSON.stringify(players));

// [ Object { name: "Tyler", score: 22 }, Object { name: "Ryan", score: 41 } ]

localStorage limits in browsers

Mobile browsers:

BrowserGoogle ChromeAndroid BrowserFirefoxiOS Safari
Space available10MB2MB10MB5MB

Desktop browsers:

BrowserGoogle ChromeOperaFirefoxSafariInternet Explorer
Space available10MB10MB10MB5MB10MB

Storage events

Whenever a value in set in localStorage, a storage event will be dispatched on all other windows from the same origin. This can be used to synchronize state between different pages without reloading or communicating with a server. For example, we can reflect the value of an input element as paragraph text in another window:

First Window
var input = document.createElement('input');

input.value = localStorage.getItem('user-value');

input.oninput = function(event) {
  localStorage.setItem('user-value', input.value);
Second Window
var output = document.createElement('p');

output.textContent = localStorage.getItem('user-value');

window.addEventListener('storage', function(event) {
  if (event.key === 'user-value') {
    output.textContent = event.newValue;


Event is not fired or catchable under Chrome, Edge and Safari if domain was modified through script.

First window
// page url:
document.domain = '';

var input = document.createElement('input');

input.value = localStorage.getItem('user-value');

input.oninput = function(event) {
  localStorage.setItem('user-value', input.value);
Second Window
// page url:
document.domain = '';

var output = document.createElement('p');

// Listener will never called under Chrome(53), Edge and Safari(10.0).
window.addEventListener('storage', function(event) {
  if (event.key === 'user-value') {
    output.textContent = event.newValue;


The sessionStorage object implements the same Storage interface as localStorage. However, instead of being shared with all pages from the same origin, sessionStorage data is stored separately for every window/tab. Stored data persists between pages in that window/tab for as long as it's open, but is visible nowhere else.

var audio = document.querySelector('audio');

// Maintain the volume if the user clicks a link then navigates back here.
audio.volume = Number(sessionStorage.getItem('volume') || 1.0);
audio.onvolumechange = function(event) {
  sessionStorage.setItem('volume', audio.volume);

Save data to sessionStorage

sessionStorage.setItem('key', 'value');

Get saved data from sessionStorage

var data = sessionStorage.getItem('key');

Remove saved data from sessionStorage


Clearing storage

To clear the storage, simply run


Error conditions

Most browsers, when configured to block cookies, will also block localStorage. Attempts to use it will result in an exception. Do not forget to manage these cases.

var video = document.querySelector('video')
try {
    video.volume = localStorage.getItem('volume')
} catch (error) {
    alert('If you\'d like your volume saved, turn on cookies')

If error were not handled, program would stop functioning properly.

Remove Storage Item

To remove a specific item from the browser Storage (the opposite of setItem) use removeItem



localStorage.setItem("greet", "hi");

console.log( localStorage.getItem("greet") ); // null

(Same applies for sessionStorage)

Simpler way of handling Storage

localStorage, sessionStorage are JavaScript Objects and you can treat them as such.
Instead of using Storage Methods like .getItem(), .setItem(), etc… here's a simpler alternative:

// Set
localStorage.greet = "Hi!"; // Same as: window.localStorage.setItem("greet", "Hi!");

// Get
localStorage.greet;         // Same as: window.localStorage.getItem("greet");

// Remove item
delete localStorage.greet;  // Same as: window.localStorage.removeItem("greet");

// Clear storage


// Store values (Strings, Numbers)
localStorage.hello = "Hello";
localStorage.year  = 2017;    

// Store complex data (Objects, Arrays)
var user = {name:"John", surname:"Doe", books:["A","B"]};
localStorage.user = JSON.stringify( user );

// Important: Numbers are stored as String
console.log( typeof localStorage.year ); // String

// Retrieve values
var someYear = localStorage.year; // "2017"

// Retrieve complex data
var userData = JSON.parse( localStorage.user );
var userName =; // "John"

// Remove specific data
delete localStorage.year; 

// Clear (delete) all stored data

localStorage length

localStorage.length property returns an integer number indicating the number of elements in the localStorage


Set Items

localStorage.setItem('StackOverflow', 'Documentation');
localStorage.setItem('font', 'Helvetica');
localStorage.setItem('image', 'sprite.svg');

Get length

localStorage.length; // 3

Got any JavaScript Question?