Both localStorage
and sessionStorage
objects provide the same methods and properties because they return the same Storage object.
The Storage
object has just one property, length
, that returns the number of items stored in it.
Here is a list of methods that you can call to manipulate web storage data:
METHOD | DESCRIPTION |
---|---|
setItem(key, value) |
Add a new key-value pair to the storage |
getItem(key) |
Retrieve a value by its key |
removeItem(key) |
Remove an item by its key |
clear() |
Delete all key-value pairs |
key(n) |
Retrieve the name of the nth key in the storage |
Let us play with localStorage
to get an idea of how web storage works.
The following example uses setItem()
to add new key-value pairs to localStorage
:
localStorage.setItem('id', 'ATS-456');
localStorage.setItem('email', 'john.doe@example.com');
Note that both key and value passed to setItem()
must be strings. If you pass any value that is not a string, like an object or a number, the setItem()
method will automatically convert it a string:
localStorage.setItem('visitors', 34); // stored as '34'
localStorage.setItem('user', { name: 'Alex' }); // stored as '[oject Object]'