How to use window.localStorage

Published on: June 3, 2017

Welcome to the 50th Easy JavaScript tutorial, part of EasyProgramming.net. Did you know that you can store information in your browser to hold onto for the whole session? Even if you reload the page? Today, let's cover window.localStorage. We will utlize the JSON.stringify method in this tutorial. Check out the tutorial to learn about JSON.stringify.

HTML5 allows you to store information directly to your browser's memory, instead of cookies. Although cookies can last longer and span multiple sessions, localStorage is excellent for keeping temporary data in a current session without using cookies. And unlike cookies, you can store up to 5MB of data. That's a lot of data! (One character is 8-bits or 1 byte, and 1 megabyte is 1 Million bytes!).

window.localStorage will keep the information based on the domain without an expiration. window.sessionStorage also exists, which will dete the data as soon as the browser tab is closed.

Let's take a look at the Syntax of window.localStorage:

    //set a localStorage item - first argument is the key of the item, followed by the value, which should be a string
    window.localStorage.setItem("nameOfItem", JSON_string);

    //retrieve a localStorage item - only argument needed is the name/key of the object - store it in a variable
    var getItem = localStorage.getItem("nameOfItem");

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/18585ubs/

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:

Comments: