Explain Codes LogoExplain Codes Logo

How to check whether a Storage item is set?

javascript
prompt-engineering
best-practices
localstorage
Alex KataevbyAlex Kataev·Jan 2, 2025
TLDR

Validate a Storage item's presence using getItem, which returns null for non-existent items.

if (localStorage.getItem('key') !== null) { // Our item's chilling right here! } else { // The item's on a vacation! }

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:

const item = localStorage.getItem('key') || 'defaultValue'; // If absent, greet 'defaultValue'!

Embracing modern JavaScript for simplicity

Use modern JavaScript features to make your code look like a poem:

  • Optional Chaining (?.): Prevents a chilling encounter with TypeError if localStorage is undefined.
  • Nullish Coalescing Operator (??): Meet your knight in shining armor when you face null or undefined.
const item = localStorage.getItem('key') ?? 'defaultValue'; // Null Terminator!

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.

if(localStorage.getItem('key')) { // It's hammer time! }

Also, localStorage isn't the Mariana Trench. It's got a storage limit. Too much setItem, and you'll hit the roof!

try { localStorage.setItem('key', 'value'); // Trying to squeeze one more into the room! } catch (e) { if(e instanceof DOMException && e.code === 22) { // Phew! That's a crowd. Storage is full! } }

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

// Two items, One-liner! Efficiency? Check. localStorage.setItem('key1', 'value1').setItem('key2', 'value2');

Swipe or wipe? You decide.

// Clean with care. One item at a time. if(localStorage.getItem('someKey')) { localStorage.removeItem('someKey'); // Sorry, someKey. It’s not you, it’s me. }

Cleaning the slate

// Blank slate. Because, who doesn’t like a fresh start? if(confirm('Clean up the garage?')) { localStorage.clear(); // localStorage, meet Soap. }