By the end of this chapter, you should be able to:
localStorageto save information in the browser
localStorage is a mechanism for storing information in the browser for a specific domain. The API is quite easy to use and very minimal - so let's get started with it!
You can read more about it here
When you read more about
localStorage you will also hear about something called
sessionStorage. MDN explains them both this way:
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
What this basically means is:
sessionStorage maintains a separate storage area for each given origin that's available for the duration of the page session (as long as the browser is open, including page reloads and restores)
localStorage does the same thing, but persists even when the browser is closed and reopened.
The most important thing to remember is that all of your keys in
sessionStorage must be STRINGS.
localStorage stores everything as strings, so it's just good to get in the habit of setting your keys as strings to avoid confusion.
To set something into localStorage we use the
setItem method and to retrieve we use the
getItem method (only passing in the key)
localStorage.setItem("instructor", "Elie"); localStorage.setItem("favoriteNumber", 18); localStorage.setItem("isHilarious", true); localStorage.getItem("instructor"); // "Elie"
If you refresh the page - you should be able to still retrieve these keys in
localStorage! Try it out a bit more!
To delete a key we use the
removeItem function, and to clear everything from
localStorage for this domain we use
So far we have only added primitives, which is nice and easy, but what happens when we start adding objects? Well, things get a bit trickier.... Let's see what happens:
var instructors = ["Elie", "Matt", "Tim"]; localStorage.setItem("instructors", instructors); localStorage.getItem("instructors");
When we get the instructors from
localStorage, we don't have an array anymore - we have a string! Remember, when dealing with
localStorage, everything gets converted into a string.
In order to get back our original data type, we need to briefly introduce something called JSON. Right now we are going to cover this quickly, but we will be discussing it quite a bit more later on.
Using these two methods allows us to preserve the intended data structure when it is something other than a string:
When you're ready, move on to Events Exercises