# Web Storage
# Local Storage
Each browser has the ability to save some data on behalf of each domain that the user visits. There is a maximum amount of memory allocated to each domain, which varies depending on the browser. When the maximum amount for the domain or the browser as a whole is reached then it is up to the browser what will be deleted.
localStorage
is a high level object inside window
, just like document
and navigator
.
All the data that gets saved must be something that can be represented as a String. that is because it saves the data as a JSON
String.
Each JSON
String will be stored under a key. The key
must be a string name, just like the properties in any normal JavaScript Object. Each key's value can be a single primitive value or it can be a complex combination of Arrays and Objects which have been converted into a JSON
String. Each key
must be unique for that domain.
REMEMBER that
localhost
is a domain shared by every website you will ever test.
To retrieve data from localStorage
we call the getItem(key)
method. We must provide the name of the key to retrieve. If the key does not exist then null
is returned. Always check for a valid returned value.
The value that is returned from getItem
must be converted from a String into an Object with the JSON.parse()
method.
let myData;
let key = 'highscores';
let dataStr = localStorage.getItem(key);
if (dataStr) {
myData = JSON.parse(dataStr);
}
2
3
4
5
6
When you want to create or update the value of some key in localStorage
you MUST overwrite the old value with an entirely new value.
The method we would use for the add or update is setItem(key, val)
. It needs a key and the new value that will replace the old one.
Before we send the new data to localStorage
it must be converted into a JSON String with the JSON.stringify
method.
myData = ['a', 'new', 'or', 'updated', 'array'];
dataStr = JSON.stringify(myData);
localStorage.setItem(key, dataStr);
2
3
REMEMBER all the data going in and out of webstorage must be a String.
If you want to empty everything in Web Storage for a domain, use the localStorage.clear()
method.
If you want to delete a single key's value in Web Storage then we would use the localStorage.removeItem(key)
method.
There is only one property in localStorage
- .length
. It will tell you how many keys exist for the current domain.
The last method that exists for Web Storage is the localStorage.key(n)
method. It accepts a numeric index number and returns the name of the key
at that position in web storage.
MDN Reference for LocalStorage
MDN Reference for SessionStorage
# Session Storage
Session Storage has the exact same methods and properties and abilities as localStorage
. The difference is that when the browser tab is closed or the browser is shut down then all the stored data is marked for deletion.
When it comes to the methods in sessionStorage
, they are the same as the localStorage
ones. Just replace local
with session
and they will all work.