How to check whether a Storage item is set?
Validate a Storage item's presence using getItem
, which returns null
for non-existent items.
Single line default setting
Sometimes, you may want to set a default value when the item is not found. Save your keystrokes by using the logical OR operator:
Embracing modern JavaScript for simplicity
Use modern JavaScript features to make your code look like a poem:
- Optional Chaining (
?.
): Prevents a chilling encounter withTypeError
iflocalStorage
is undefined. - Nullish Coalescing Operator (
??
): Meet your knight in shining armor when you facenull
orundefined
.
In the corner with common pitfalls
.hasOwnProperty()
and localStorage
are as compatible as cats and water, and for the same reason! Don't use the 'in'
operator either, that guy cares too much about the whole family tree - the Prototype Chain. Drop the typeof
check too, getItem()
will handle the existence hassle.
Error-proofing and checks
Before you gear up for manipulation, ensure the item exists.
Also, localStorage isn't the Mariana Trench. It's got a storage limit. Too much setItem
, and you'll hit the roof!
Manage your LocalStorage like a Pro
Efficiency and simplicity are your keys to becoming a localStorage Jedi. Here’s how you can achieve that:
Setting more with less
Swipe or wipe? You decide.
Cleaning the slate
Was this article helpful?