0

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?

  • 2
    possible duplicate of [Specify default value for HTML5 Local Storage item?](http://stackoverflow.com/questions/13791569/specify-default-value-for-html5-local-storage-item) – James Thorpe Jun 26 '15 at 08:16

2 Answers2

5

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.

DEMO


Or, Simple if expression

var lang = localStorage.getItem('NG_TRANSLATE_LANG_KEY');
if(!lang){
   lang = 'en';
}
Satpal
  • 132,252
  • 13
  • 159
  • 168
  • 3
    Whoever downvoted that answer should explain why. Understanding that the question is a duplicate (there are tons of questions about short-circuit evaluation) I don't see why such an answer should be downvoted, since it is valid and complete. – briosheje Jun 26 '15 at 08:06
  • @briosheje I didn't DV the answer (I did the question - as you say, there's tons of stuff about this), but you often see people DVing answers on questions like this as "not useful" using the argument that it encourages this sort of "I'll just ask without trying to figure it out myself because I know someone will just tell me" questions. – James Thorpe Jun 26 '15 at 08:10
  • @JamesThorpe: I completely agree, but as long as you think that a question should not exist (because is a duplicate or whatever) you can just flag such a question, if someone is brave and on a good moon and wants to answer (because he either think that it is not a duplicate or whatever) he is free to do that, I don't understand why downvoting a valid answer :P. In any case, to stay ontopic, he could also do: `var lang = !localStorage.getItem('NG_TRANSLATE_LANG_KEY') && 'en';`, which should be equivalent to the if written after the edit. – briosheje Jun 26 '15 at 08:13
0

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';
user1438038
  • 5,821
  • 6
  • 60
  • 94