简体   繁体   中英

What is the right way for using ternary operator inside string templates?

I have a getter that has to return a different value depending on existed props. It looks like:

const converter = ({ propsValue }) => {
  return {
     get label() {
         return `${propsValue} ? ${propsValue} : ${anotherValue} ${secondAnotherValue}`
      } 
   }
}

The question is: What is the right syntax for the ternary operator inside string templates literals?

You need to put condition in brackets

const converter = ({ propsValue }) => {
  return {
     get label() {
         return `${propsValue ? propsValue : 'anotherValue'}`
      } 
   }
}

With dynamic value

return `${propsValue ? propsValue : anotherValue}`;

With two dynamic values

return propsValue ? propsValue : `${anotherValue} ${secondAnotherValue}`;

OR

return `${propsValue ? propsValue : anotherValue + ' ' + secondAnotherValue}`;

Answers are there for using the ternary operator

However, if you would like to look for a shorter and better one I would like to suggest one more thing if you just checking the first string in this way, you can also use it like

Solution without using ternary operator

return `${(propsValue ||anotherValue)}`

However, if you have multiple dynamic values you can still use it as

return `${(propsValue ||anotherValue + oneMoreValueHere)}`

and to apply the same in your code,

const converter = ({ propsValue }) => {
  return {
     get label() {
           return `${(propsValue ||anotherValue + oneMoreValueHere)}`
      } 
   }
}

The way to do it inside the quotes would be
return `${propsValue? propsValue: anotherValue} ${secondAnotherValue}`
yet a better way to do it would be using the or operator like this:
return `${propsValue || anotherValue} ${secondAnotherValue}`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM