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.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.