'Specify default value for HTML5 Local Storage item?

In the case that you are trying to get a local storage item that doesn't exist, is it possible to set a default value for that item?

For example, let's say that in your web app, various UI preferences are saved in local storage. When a user leaves your website and then comes back, the UI is setup according to the values pulled from their local storage. This works great.

However, when a user visits your web app for the first time, those local storage values do not exist yet. So when your JavaScript attempts to get those local storage items, they will all be undefined. Is there not a way to specify default values for each local storage item in the case that it doesn't exist?

Most programming languages that deal with saving key/value pairs offer some sort way to specify default values (think .ini config file interfaces). I was expecting something like this:

var preference = localStorage.getItem('some-key', 'Default Value');

Also, I know that I can easily programmatically set default values by testing if they are null/undefined or not and set the value accordingly, but I wanted to see if this was built into the local storage key/value pair fetching and that maybe I just wasn't seeing it. If this feature doesn't exist, I will end up just writing some basic local storage wrapper functions that add in this feature.



Solution 1:[1]

No, there is no such built-in functionality. See the spec for the Storage interface:

interface Storage {
  readonly attribute unsigned long length;
  DOMString? key(unsigned long index);
  getter DOMString getItem(DOMString key);
  setter creator void setItem(DOMString key, DOMString value);
  deleter void removeItem(DOMString key);
  void clear();
};

And the following line just to confirm that further:

The getItem(key) method must return the current value associated with the given key. If the given key does not exist in the list associated with the object then this method must return null.

You can just use the usual techniques. Something like this should be fine:

var preference = localStorage.getItem('some-key') || 'Default Value';

Solution 2:[2]

The solution from James:

var preference = localStorage.getItem('some-key') || 'Default Value';

Only works if you never save empty strings OR booleans OR if your variable can be 0.

Solution which is longer but always works:

var preference = localStorage.getItem('some-key');
if(null === preference)
{
    preference = 'Default Value';
}

Solution 3:[3]

You can use this method for objects

/*
Helper function that return an object from local storage or a default value
*/
function getObjectFromLocalstorage(key, default_value){
  var value = localStorage.getItem(key);
  if (value === null){
    return default_value;
  }
  return JSON.parse(value);
}

And here are some example outputs:

console.log(getObjectFromLocalstorage("some_undefined_key", {}));
>>> {}

console.log(getObjectFromLocalstorage("some_undefined_key", []));
>>> []

var value = {a: 1}; 
localStorage.setItem("defined_key", JSON.stringify(value));
getObjectFromLocalstorage("defined_key", {});
>>> {a: 1}

Solution 4:[4]

The best way is simple check when load the page

let preference = localStorage.getItem('some-key');

window.addEventListener("load", () => {
  if (null === preference) {
    localStorage.setItem("some-key", "Default Value");
  }
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James Allardice
Solution 2 Mathieu Bulliot
Solution 3 Roei Bahumi
Solution 4 Ericc Eacs