HTML and CSS Reference
In-Depth Information
If sessionStorage had stored the value as a number, you would
see an alert box showing 17. Instead, the cost of $12 was saved
as a string. Because JavaScript uses the same method for con-
catenation as it does for addition (for example, the plus symbol),
JavaScript sees this as appending a number to a string—so the
alert box actually shows 125—much more than you'd probably
be willing to pay to watch any video of Bruce! What's going on
here is type coercion: upon storing the data in the storage API,
the data type is coerced into a string.
Finally, it's worth noting that if the key doesn't exist when you
call getItem , the storage API will return null. If you're planning to
use the storage API to initialise values, which is quite possible,
test for null before proceeding because it can throw a pretty
nasty spanner in the works if you try to treat null as any other
type of object.
Ways to access storage
Yo u ' r e p r o b a b l y t h i n k i n g , “ H a n g o n a m i n u t e , R e m y s h o w e d m e
how to grok web storage in 15 seconds, but how does all this
getItem , setItem stuff relate?” I'm glad you're paying attention.
If you look back at the API, you'll see that getItem , setItem, and
removeItem are a getter , setter, and deleter , respectively. This
means that when we call delete localStorage.superVillain ,
JavaScript is making a call to removeItem for us. Of course, if you
spotted that already, good for you. Pat yourself on the back.
An expando is a short and expressive way of getting, setting,
and deleting data out of the storage object, and as both ses-
sionStorage and localStorage descend from the Web Storage
API, they both support this method of accessing the data.
Using our example of storing a Twitter screen name, we can do
the same thing using expandos:
sessionStorage.twitter = '@rem';
alert( sessionStorage.twitter ); // shows @rem
Remember the expando method of storing values is also subject
to the “stringifying” of values as we saw in the previous exam-
ple, with Bruce's video website, because it's going via the setter
method of setItem .
Search WWH ::

Custom Search