localStorage and sessionStorage in JavaScript

2 Comments

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

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

This prints:

To delete a variable, we use:

localStorage.removeItem('examplevariable');

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:

localStorage.clear();

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.

sessionStorage

This works in a similar way. For example:

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

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.

Objects

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');
    console.log(JSON.parse(a));

This produces:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

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

carldesouza.comLinkedIn Twitter | YouTube

 

2 Responses to localStorage and sessionStorage in JavaScript

Leave a Reply

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