Madeline Zenz Logo
MADELINE ZENZ

Local Storage

Browsers use a key/value database to store many things. This is called the local storage. Here is an example of what it looks like in the browser.

local storage example


The key is the identifier which acts almost like an address. The value is what is being stored. In this example, if you got the value of the key “cats”, it would return an array of cats.

The API of the localStorage object consists of these methods:

  • setItem(key, value)
  • getItem(key)
  • key(index)
  • clear()



setItem


This method allows you to create a new key/value pair in the localStorage object.
One thing that should be noted is that keys/values can only be stored as keys in the local storage. We would normally make the “vaccinated” variable a Boolean but with local storage we have to set it to a string value.

            
                    localStorage.setItem("name", "Sugar");
                    localStorage.setItem("age", "3");
                    localStorage.setItem("vaccinated", "true");
            
        


getItem


This method allows us to get a value from the local storage using its key. In this example, we bind the value to an element on the page.

            
                document.getElementById("name").innerHTML= localStorage.getItem("name");
            
        


key


This method is helpful when looping through keys. The parameter takes a number (the index of the key). The method returns the name of the key.

            
                let KeyName = localStorage.key(index);
            
        


clear


This method clears all of the data from the localStorage object. There should be some validation put in place before running this code to prevent accidentally clearing the database.

            
                localStorage.clear();
            
        

There are many uses for local storage, but for now these are just basics on what it is and its API.