The localStorage is an object literal, so the following the safest way
to test for it when reading from is:
var a = function (x) {
if (typeof localStorage !== "undefined" && localStorage.hasOwnProperty(x)) {
//do something.
}
};
The above example ensures that localStorage is a known name and if so
then checks for the existence of a known property. If localStorage is
value null it still reports as type object, which it will inherit from
the object prototype that contains the "hasOwnProperty" method.
If you plan on setting a new value in localStorage then you will not
have the benefit of using the "hasOwnProperty" method, but you can test
for null explicitly. In my opinion this represents a fringe case, so
I wouldn't even bother. I say this because I am using localStorage in
all the applications I write in my personal time and nobody has reported
such errors.
In my opinion the only condition you should be worried about is where
localStorage is undefined. In that case simply provide the appropriate
alternate application experience.
I choose to never use try/catch blocks, because I do not find them
helpful. If there are known errors in my code I would rather correct
then than mitigate them. If there are errors from something beyond my
control, such as user input, then I would prefer to return a response
informing the user of their error.
Thanks,
Austin Cheney, CISSP
--
To view archived discussions from the original JSMentors Mailman list:
http://www.mail-archive.com/[email protected]/
To search via a non-Google archive, visit here:
http://www.mail-archive.com/[email protected]/
To unsubscribe from this group, send email to
[email protected]