Mahma Deva
Mahma Deva

Reputation: 566

Nesting ternary operator properly

I am displaying a table with animals using a framework, that restricts me in using a single ternary operator for displaying and formatting my text, the idea is this: if the object contains animalType, animalType.name and animalType.id, then check if the string that consists of the name + id is longer than 10 characters, truncate the text, else if its less than 10, show entire text and if they do not exits, display an empty title, here is how I would write that using regular if else statement:

if(animalType && animalType.name && animalType.id) {
  if ((animalType.name + animalType.id).length > 10) {
    return animalType.name + animalType.id.slice(0, 10) + '......'
  } else if ((animalType.name + animalType.id).length < 10) {
    return animalType.name + animalType.id
  }
} else {
  return ''
}

By reading the mdn web docs, I understand that multiple conditions can be passed by:

condition1 ? value1 : condition2 ? value2

and here is my attempt using ternary operator:

animalType && animalType.name && animalType.id
  ? (animalType.name + animalType.id).length > 10
  : (animalType.name && animalType.id).slice(0, 10)
  : (animalType.name + animalType.id).length < 10
  ? animalType.name && animalType.id
  : ''

But I don't get how to wrap the ternary operator so that it starts the check after it has evaluated whether the name and id exist, like one would do in a regular if else statement, how can I write the same logic using ternary operator?

Upvotes: 0

Views: 63

Answers (2)

pteranobyte
pteranobyte

Reputation: 594

I will write your case like this just so I don't write animalType a thousand times:

if(conditionA) {
    if(conditionB) {
        return value1
    } else if (conditionC) {
        return value2
    }
} else {
    return value3
}

This you could do with the ternary operator like this:

return conditionA
    ? conditionB
        ? value1
        : conditionC
            ? value2
            : undefined
    : value3

Upvotes: 0

john Smith
john Smith

Reputation: 17906

just follow this way of bracketing, you may have to adjust your logic so your next conditions alway follow the : and you have to be precise about the brackets, in your question there are even unclosed brackets! use a texteditor that highlight the start and end-brackets if you need to have it like this

condition ? value : (condition ? value : (condition ? value : (and ? so : on) ))

without this explicit bracketing it´s my experience that it may fail.

in javascript you should also be able to wrap your logic into a function and wherever you want to place the ternary just put the function()

Upvotes: 0

Related Questions