localStorage and sessionStorage in JavaScript

Leave a comment

In JavaScript, there are 2 ways to store data within a web browser:

  • localStorage, which can be used to save data across browser sessions
  • sessionStorage, which stores data for the page session


    localStorage.setItem('examplevariable', '123');
    var a = localStorage.getItem("examplevariable");

This prints:

To delete a variable, we use:


If we try to access the variable after deleting, it will return null.

If we set the item in localStorage and close the web browser, we will still be able to retrieve it after closing.

To clear all storage, use:


If you type localStorage into the console, it will return what is current in localStorage:

You can also see the storage (in Chrome) by selecting F12 and navigating to Application->Storage:

Note there is no expiration of the localStorage variables, but you can control this through code by adding a timestamp to the localStorage and decide when to remove items.


This works in a similar way. For example:

    sessionStorage.setItem('examplesessionvariable', '456');
    var a = sessionStorage.getItem("examplesessionvariable");

This produces:

If the user closes the browser, the sessionStorage is wiped out, so trying to retrieve a variable will result in null. You can also removeItem() and clear() in the same way.


To store objects in localStorage or sessionStorage, we can use JSON stringify and parse.

For example:

    var customer = {'name':'Bob', 'phone':'(111) 222-3456'};
    sessionStorage.setItem('customer', JSON.stringify(customer));
    var a = sessionStorage.getItem('customer');

This produces:



Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube


Leave a Reply

Your email address will not be published. Required fields are marked *