How to Check if a Key Exists in localStorage Using JavaScript?

Since the Storage object (which is accessed via window.localStorage property) has no hasItem() method, you can simply use the getItem() method instead to check if an item is set or not (as it returns null when the key does not exist). For example:

const itemSet = (localStorage.getItem('nonExistent') !== null);

if (itemSet)  {
    // ...
}

If you're thinking this might conflict with a null value that is stored in the localStorage, then you should not worry because localStorage only stores string values and 'null' !== null.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.