Search code examples
javascriptfallback

How to use fallback for some specific value, instead of undefined, in Javascript?


I want to use Javascript variable fallback to assign default value when a particular condition is met, instead of undefined.

I understand I can use simple if-else to achieve the same result. I want to know whether I can use fallback for it or not. For example, can I do something like:

var cat = 'cat';
var animal = (cat == 'cat') || ('dog');

which currently gives,

Type 'true' is not assignable to type 'string'.

I want something with functionality similar to

var cat = 'cat';
if(cat==='cat')
{
    var animal = cat;
} else 
{
    var animal = 'dog';
}

Solution

  • It sounds like you want the conditional operator:

    var animal = cat == 'cat' ? cat : 'dog';
    

    If you really really wanted to use || for this, you could chain a && cat onto the cat === 'cat', and then alternate with 'dog':

    var cat = 'cat';
    var animal = (cat === 'cat' && cat) || 'dog';
    console.log(animal);

    (please don't do this, though)