How can I rewrite this with Ternary Operator?


#1

Hi,
How can I rewrite this with Ternary Operator?

face.textContent = result == 0 ? headNr + ' times ' + resultFace : tailNr + ' times ' + resultFace;

I tried everything, but couldn’t find a way.

Thanks


#2

It’s already using it. Do you mean without using the ternary operator?


#3

Sorry, I tried so many different things that I asked the wrong question in confusion.
Actually, I wanted to rewrite this ternary operation with Template Literal.
I tried the following but it’s not working:

face.textContent = `${result} == 0 ? ${headNr} times ${resultFace} : ${tailNr} times ${resultFace}`;

#4

There are a couple of ways to do this. The thing to keep in mind is that everything in `…` that is not within ${...} is considered a string. The only way the ternary will work if you try to wrap the whole thing in a template literal is if you also wrap the whole thing in a single template literal expression.

`${result == 0 ? headNr + ' times ' + resultFace : tailNr + ' times ' + resultFace}`;

but that defeats the purpose.

So instead, you’ll just use template literals where you have strings, adding in the expressions where you have variables.

result == 0 ? `${headNr} times ${resultFace}` : `${tailNr} times ${resultFace}`;

You can simplify this further by breaking out the duplication and using a falsy check for result.

`${result ? tailNr : headNr} times ${resultFace}`;