localStorage is a window property that allows you store data locally within the website origin. The data save in localStorage will still be available even after you close the browser, or even if you come back tomorrow, or next week, or even next year.
How to access localStorage?
Here are some ways to access localStorage:
window.localStorage();
window
object.const storage = window.localStorage();
What are the localStorage methods?
- setItem() - Add a key-value pair data
- getItem() - Retrieve a data by key
- removeItem() - Remove an item by key
- clear(): Clear all data from localStorage
setItem(key, value)
Add a key-value pair data. The first argument is the key or the unique identifier for the value. The send argument is the a String
. If you want to store and Object
to localStorage
, you must stringify
it first.
Store a String
window.localStorage.setItem('hello', 'world');

Storge an Object
// The Object we want to store
const greeting = {
greeting: 'Hello World!'
};
// The stringified version of the Object using JSON.stringify.
const stringified = JSON.stringify(greeting);
// Set the data to localStorage
window.localStorage.setItem('greeting', stringified);

getItem(key)
The argument is the key or unique identifier for the data stored in localStorage
. Let's retrieve the Object
we stored from the first example.
// The string version of the Object.
const stringified = window.localStorage.getItem('greeting');
// We are converting the the stringified value
// back to its Object form.
const greeting = JSON.parse(stringified);
console.log(greeting);
/**
* {
* greeting: 'Hello World!'
* }
*/

removeItem(key)
Remove a single item by key or unique identifier from localStorage
window.localStorge.removeItem('greeting');
clear()
This method will delete all data in the localStorage
.
window.localStorage.clear();
Notes
Take note the the data in the localStorage
is only present per origin
meaning, the localStorage
data in www.website1.com is not present in www.website2.com.