Java Reference
In-Depth Information
getting data
Retrieving data from local storage is just as straightforward as setting it. With the
getItem()
method, you supply the key for which you want the value of:
var name = localStorage.getItem("userName");
This code uses the
getItem()
method to retrieve the value associated with the "
userName
" key and
assigns that value to the
name
variable. In the case of the example from the previous section,
name
would contain "
Paul
".
You can also use the key as
localStorage
is property if it is a valid identifier:
var name = localStorage.userName;
This code also gets the value of
Paul
and assigns it to the
name
variable.
A word of note: Keys are case‐sensitive. That may seem obvious if you are using
object
.propertyName
syntax, but the rule applies to
setItem()
and
getItem()
. For example:
localStorage.setItem("userName", "Paul");
var name = localStorage.getItem("UserName"); // null
This code set a key of
userName
with a value of
Paul
. It then tries to retrieve a value with the key of
UserName
. Because of the uppercase
U
,
UserName
and
userName
are two different keys. We haven't
set a value with
UserName
, so
getItem()
returns
null
.
removing data
Eventually, you will want to remove some data that you stored in local storage, and you can do that
with the
removeItem()
method. Simply provide the key you want to remove, and the key/value pair
will be deleted from local storage. For example:
localStorage.removeItem("userName");
This code deletes the
userName/Paul
key/value pair from local storage. If the key is a valid
JavaScript identifier, you can also use
object.propertyName
syntax to do the same thing, like so:
localStorage.userName = null;
Here, you assign the value of null to the
userName
key/property, thus removing the key/value pair
from local storage.
If your goal is to remove all keys and values from local storage, you can use the
clear()
method,
like this:
localStorage.clear(); // no more key/value pairs
storing data as strings
It's important to note that web storage is a string‐only data store. This means that keys and their
values can only be strings. If you try to store some other type of value (like a number) or object, it is