If ternary operators are the same as if/else, why use them at all?

general question:
if “Ternary Operator” is kinda same, shortcut to if-else statement, it’s more convenient
for me to use if-else statement for now, can I avoid ternary operators?

9 Likes

By all means, yes. Avoid them all you please. Mind, we would be remiss to avoid their utility and simplicity.

It comes down to where in one’s mind conditional logic is firing. The step from one to the other is right there; one has but to take it.

if (a) {
    return true;
} else {
    return false;
}

versus,

return a ? true : false;

If you want to toggle an infinite loop,

return a ? false : true;

which is the same as,

return ! a;
34 Likes

Thanks for your explanation, I find the ternary operator very difficult to use but after i re-take my exercise from the beginning of JS i find it more simple to use. What about else if statement argument how can we do it if we have more else if statement Please…Thanks and moreover How can we know which operator to use for a project for instance switch operator, if/else or ternary operator. Please guide us we are beginners.
{Thanks YOU}

Best advice for beginners is to stick with what you know, for now. If you are going to use a ternary, keep it simple and be sure your logic is sound. Just because we can write seemingly elegant code doesn’t mean it is the best way to do it. Is it maintainable? Is it easy to read and understand like ifelse ifelse?

6 Likes

Thanks for your kind advice. Please, can you tell me while am getting error when am trying to convert this if, else if, else to ternary operator. i am getting the error after the second console.log Thanks once again

/*let athleteFinalPosition = ‘first place’;

if (athleteFinalPosition) {

  console.log('You get the gold medal!');

} else if (athleteFinalPosition === ‘second place’) {

console.log('You get the silver medal!');

}

else if (athleteFinalPosition === ‘third place’) {

console.log('You get the bronze medal!');

}

else {console.log(‘No medal awarded.’);}*/

Ternary Operator.

let athleteFinalPosition = ‘first place’;

  athleteFinalPosition ? console.log('You get the gold medal!') : console.log('You get the silver medal!') : console.log('You get the bronze medal!')

The thing to note about the difference between an if..else and a ternary is that the former is a statement and the latter is an expression. We can put the whole thing into console.log() (or anywhere that serves).

x = athleteFinalPosition

console.log(`You get the ${
  x === 'first place' ? `gold` : 
  x === 'second place' ? `silver` : 
  x === 'third place' ? `bronze` :
  `tin`} medal!`)

Note the final case in the ternary. That is the default. Set athleteFinalPosition to fourth place to see how this works out.

Don’t let the good looks fool you. There is no tin medal. An if statement would give us a way around this tiny discrepancy. It’s not off the table, yet.


The appropriate time to use a ternary usually presents itself when other approaches go overboard or it fits nicely with the pattern.

The pattern we see here presented is one of mixing string literals. As a ternary, or even a full blown if conditional there is a lot of text. What if we pack all that text into a nice little package and let it do the work, rather than be the work?

x = athleteFinalPosition

podium = {
'first place': 'gold',
'second place': 'silver',
'third place': 'bronze'
}
if (podium.hasOwnProperty(x)) {
  console.log(`You get the ${podium[x]} medal!`)
} else {
  console.log(`You get the experience.`)
}

or better still,

console.log(
  `You get the ${
    podium.hasOwnProperty(x) ? 
    `${podium[x]} medal!` : 
    `experience.`
  }`
)
4 Likes

How will this create an infinite loop?

It can be toggled indefinitely. To break the loop some other condition would be needed.

How? I’m not really sure how to make it infinite. Can you show me an example?

const toggle = a => ! a
let x = false
while (true) {
  console.log(x = toggle(x))
  if (Math.floor(Math.random() * 10) === 5) {
    break
  }
}

Example output

true
false
true
false
true
false
true
false
true
false
true

Ok! So if I understood correctly, the toggle function takes in an argument and applies the NOT operator to this value, then returns it. E.g. toggle(2) would return false as 2 is a truthy value and !2 = false. Then, while(true) creates an infinite loop. Inside this loop, we logged x = toggle(x). I didn’t really understand this, but I’m guessing that we are assigning the returned value of the toggle function with an argument of x to the x variable. So the initial value of x is false, which means that when the loop first runs, it will be equal to true. Is the value of x getting displayed on the console because the toggle function returns it? Finally, we used an if statement to break out of this loop if a random number between 0 - 9 turns out to be 5

Please correct me if I’m wrong

The new value of x is logged on return from toggle(). We can write assignments when logging.

1 Like

Great! Thank you so much!

So the new value of x is getting logged to the console because of this line:

console.log(x = toggle(x));

which is both assigning the returned value of the toggle function with an argument of x to the x variable and logging the new value of x to the console

1 Like