1

given this function

function isTastyCheese(cheeseName: string) {
    const TastyCheeses = ['camembert', 'maroilles']
    if (TastyCheeses.includes(cheeseName)) {
        return 'yes so tasty'
    }
    return undefined
}

I'd like to do something like this:

const answerCamembert = isTastyCheese('camembert') ? the_returned_value : 'no taste like sh*t' 
const answerCantal = isTastyCheese('cantal') ? the_returned_value : 'no taste like sh*t'

console.log(answerCamembert)
>>> 'yes so tasty'
console.log(answerCantal)
>>> 'no taste like sh*t'

How do i use ternary operator to do this concisely?

PS: Obsviously the function presented here is very wrong but changing it shouldn't be part of the solution

asiera
  • 492
  • 5
  • 12
  • Your solution looks fine to me. What's do you mean by _concisely_? – GigiSan Jun 09 '22 at 09:25
  • 3
    The logical OR operator is your friend here: `const answerCantal = isTastyCheese('cantal') || 'no taste like sh*t'`. Or, if you support newer platforms, the nullish coalescing operator is probably even better: `const answerCantal = isTastyCheese('cantal') ?? 'no taste like sh*t'` – Ben Aston Jun 09 '22 at 09:25
  • 2
    Or the newer, slightly more appropriate [Nullish coalescing operator (`??`)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) – Ivar Jun 09 '22 at 09:27
  • I agree with @Ben Aston, unless using a ternary operator is a mandatory requirement. – GigiSan Jun 09 '22 at 09:27
  • 1
    If this is a thought experiment, and you absolutely must use the ternary conditional operator, then the following would work (but is horrendous): `var answerCamembert = (answerCamembert = isTastyCheese('camembert')) ? answerCamembert : 'no taste like sh*t' `. Note the use of `var` to skirt around limitations of the [temporal dead zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz) associated with `let`, and assignment constraints associated with `const`. – Ben Aston Jun 09 '22 at 09:53

0 Answers0