Search code examples
javascriptconditional-statementsconditional-operator

Convert nested if/else to ternerary in React Native


Explain to me how to convert existing nested if/else to ternary operator. I looked thourgh documentation but still couldn't manage to achieve what I need.

if (value) {
  if (value.match('google')) { 
    return 'Google';
  } else if (value.match('apple')) {
    return 'Apple';
  } else {
    return 'Other websites';
  }
} else {
   return 'Number';
}

Here value is data coming from JSON. value can be link or number. I want to check if the link contains google, so show me 'google' text. If it contains apple, so show me apple text. If others just show 'others website' text. If this is not link, just show 'number' text


Solution

  • first check for value ?

    if value is there then check for value is 'google' ? if yes return:

    if value isn't google check for value is 'apple' ? if yes return:

    if value isn't apple return otherwise:

    if there is no value then return 'Number'

    let value = 'apple'
    let res = value? value.match('google')? 'Google':value.match('apple')?'Apple':'Otherwebsite':'Number';
    console.log(res)