Specify default value for HTML5 Local Storage item?
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}
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';
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';
}