I have this code:
var lang = localStorage.getItem('NG_TRANSLATE_LANG_KEY');
How can I make it default to 'en' if there is no value set in local storage?
I have this code:
var lang = localStorage.getItem('NG_TRANSLATE_LANG_KEY');
How can I make it default to 'en' if there is no value set in local storage?
You can use Short-circuit evaluation
var lang = localStorage.getItem('NG_TRANSLATE_LANG_KEY') || 'en';
The ||
returns the value of its second operand, if the first one is falsy, otherwise value of first operand is returned.
Or, Simple if expression
var lang = localStorage.getItem('NG_TRANSLATE_LANG_KEY');
if(!lang){
lang = 'en';
}
There is no feature for default values in the Webstorage API:
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.
However, you can simply define a default value when initializing your variable:
var foobar = localStorage.getItem('key') || 'default-value';