In case you are trying to get a local storage item that does not exist, is it possible to set a default value for this item?
For example, let's say that in your web application, various user interface settings are stored in local storage. When a user leaves your site and then returns, the user interface is configured according to the values derived from their local storage. This works great.
However, when a user first visits your web application, these local storage values do not yet exist. Therefore, when your JavaScript tries to get these local storage items, all of them will be undefined. Is there no way to specify default values for each local storage item in case it does not exist?
Most programming languages that deal with storing a key / value pair offer some way to specify default values (think. Interfaces to .ini configuration files). I was expecting something like this:
var preference = localStorage.getItem('some-key', 'Default Value');
Also, I know that I can easily set default values programmatically by checking if they are null / undefined or not, and setting the value accordingly, but I would like to see if this was built into a pair of local storage / value keys and maybe I just didn’t see it. If this function does not exist, I will eventually just write some basic storage shell functions that will add this function.
source share