How to Use .localStorage
What is localStorage?
It’s a property in your browser that allows you to store and save data across multiple browser sessions without an expiration. It’s like an external memory you can utilize for small features on a project.
We say small feature because the only data type you’re allowed to store in localStorage are strings.
Syntax
It’s an object that takes in a key-value pair when storing data.
Storing Data
localStorage.poop = "beef"
Using the dot-notation syntax, here we’re setting localStorage a key of “poop” to a value of “beef”.
Another syntax you could also use is the localStorage.setItem(key, value). With this syntax, we’re using the .setItem() method, passing in two parameters. The first argument is the key to accessing the data and the second is the value or the data you want to store.
localStorage.setItem('name', 'Poppy')
Accessing Data
localStorage.poop
Once again, using dot notation you can access your data with the above syntax. The alternate would be to use the .getItem() method as shown below.
localStorage.getItem('name')
You can also set a variable to the method call and access it that way.
Removing Data
localStorage.removeItem('poop')
There isn’t a dot notation for removing data but there is the .removeItem() method we can use! This method takes in the key of the data you want to remove.
As for clearing your entire localStorage, there’s the .clear() method.
localStorage.clear()
Resources: