Skip to content Skip to sidebar Skip to footer

If Localstorage Key Value Doesn't Exist

I am trying to hide my div if there is no a localStorage key value. With the line below I achieved only to hide a div when localStorage key completely deleted but need to do the s

Solution 1:

You can add required conditions using the OR operator ||

var items = window.localStorage.getItem('items')

if (items === null || items.length === 0)
{
    // items is null, [] or '' (empty string)
}

If you have to check for undefined somewhere as well you can change === null to == null or expand with an extra condition like this

if (items === undefined || items === null || items.length === 0)
{
    // items is undefined, null, [] or '' (empty string)
}

EDIT: Here is what you can do to get the array directly

var items = JSON.parse(window.localStorage.getItem('items'))

if (items === null || items.length === 0)
{
    // items is null or []
}

Solution 2:

How about simply:

if (!localStorage.nameOfYourLocalStorage) {
    // do the following if the localStorage.nameOfYourLocalStorage does not exist
}

An example of how it could be useful:

if (!localStorage.nameOfYourLocalStorage) {
    localStorage.nameOfYourLocalStorage = defaultValue;
}

Here the script will check if the localStorage name does not exist, and if it doesn't, it will create it with the default value.

And if you want it to act when it does exist, you can add an else after the if block to continue, or remove the '!' from the if block condition.

Post a Comment for "If Localstorage Key Value Doesn't Exist"