How to Use localStorage in JavaScript
HTML5 brought along cool features like the Web Storage API, which included sessionStorage
and localStorage
. It created a simple way to store data locally in the browser without affecting your application’s performance. Before Web Storage, developers used cookies, which had to be included in every HTTP request. That slowed things down. Web Storage made it easier to store key/value pairs as storage objects, and it came with more storage capacity (up to 5MB).
localStorage vs. sessionStorage: What’s the Difference?
As mentioned, Web Storage comes with two mechanisms:localStorage
and sessionStorage
. I will be covering localStorage
, but here’s a quick note on what sets them apart:
- localStorage: The data persists until you clear it. You can open and close the browser window, and your data will still be there.
- sessionStorage: Your data only lasts one session. All data will be removed after the browser window or tab is closed.
Managing Data in localStorage
First off, it’s important to know that localStorage can only store strings. However, there’s a way to get around that if you need to store an object. (We’ll get to that later.)
To store data, use the setItem()
method:
localStorage.setItem('Mushroom', 'Reishi')
To retrieve data, use the getItem()
method:
localStorage.getItem('Mushroom')
To remove data, use the removeItem()
method:
localStorage.removeItem('Mushroom')
To clear all data in localStorage, use the clear()
method:
localStorage.clear()
How to Store an Object
Since localStorage requires string values, you cannot store an object without first converting both keys and values to strings. For that, we use the JSON.stringify()
method, which converts a JavaScript object into a JSON string. To retrieve the data, you must parse the JSON string using JSON.parse()
, which converts the string back into a JavaScript object.
const Mushroom = {
Name: 'Reishi',
ScientificName: 'Ganoderma lucidum'
}localStorage.setItem('Mushroom',JSON.stringify(Mushroom))JSON.parse(localStorage.getItem('Mushroom'))
References: