javascripthtmllocal-storage

How to check whether a Storage item is set?


How can I check if an item is set in localStorage? Currently I am using

if (!(localStorage.getItem("infiniteScrollEnabled") == true || localStorage.getItem("infiniteScrollEnabled") == false)) {
    // init variable/set default variable for item
    localStorage.setItem("infiniteScrollEnabled", true);
}

Solution

  • The getItem method in the WebStorage specification, explicitly returns null if the item does not exist:

    ... If the given key does not exist in the list associated with the object then this method must return null. ...

    So, you can:

    if (localStorage.getItem("infiniteScrollEnabled") === null) {
      //...
    }
    

    See this related question: