Check if a key exists in localStorage

OpenJavaScript 0

Last updated: October 12, 2022.

If you want to retrieve something from localStorage, it is often a good idea to check if it exists first.

You can do this by checking if the return value of localStorage.getItem('key-to-check') is equal to null.

localStorage.setItem('item', 'value');

console.log(localStorage.getItem('item') !== null); 
// Logs true

console.log(localStorage.getItem('non-existent-item') !== null); 
// Logs false

The nice aspect to this solution is that even if an attempt is made to set the value associated with a key to null, it is coerced to string format ('null').

So null is only returned in the absence of an item in localStorage, even if an attempt has been made to set its value to null!

localStorage.setItem('item', null);

console.log(typeof localStorage.getItem('item')); // String
// Checks type of data for the key 'item'

console.log(localStorage.getItem('item') === null);
// Logs false because value is not actually null...

console.log(localStorage.getItem('item') === 'null');
// ...but 'null'!

The same solution also works for sessionStorage, which works in the same way but clears its contents after a user's site session.

Related links