Why won't this ternary operator work?

Here’s an if statement that works exactly as expected:

    if (sunsetMinute < 10) {
      sunsetMinute = '0' + sunsetMinute;

I tried to write this as a ternary operator, but it tells me the semicolon is an unexpected token:

sunsetMinute < 10 ? sunsetMinute = '0' + sunsetMinute;

What am I doing wrong here?

You are missing the colon section of the ternary for when the condition is false.

also this is a false use of a ternary.

The ternary returns a value. So your ternary should be of the form
sunsetMinute = (sunsetMinute < 10) ? "0"+sunsetMinute : sunsetMinute;

or more simply, use the javascript function designed to handle this:
sunsetMinute = sunsetMinute.padStart(2,"0");

or use an actual datetime construct.

1 Like

Thanks. I thought that might be the case (although I also thought I wouldn’t need it if I I didn’t have a false condition) - I tried this before posting, which also didn’t work:

sunsetMinute < 10 ? sunsetMinute = '0' + sunsetMinute : ;

After you posted your response I tried this, which fixed it:

sunsetMinute < 10 ? sunsetMinute = '0' + sunsetMinute : sunsetMinute = sunsetMinute;

I’m a bit disappointed tbh, I thought the ternary would be less verbose than the if statement.

There is an actual reason I’m not using that. Thanks for the padStart tip, I’ll keep that in mind in future.

That’s only because a ternary is a short for “if else” and you are comparing it to only an “if”. eg. compare to

if (sunsetMinute < 10) { 
  sunsetMinute = 0 + sunsetMinute; 
} else { 
  sunsetMinute = sunsetMinute; 

IMHO, you don’t need the “else” if you’re keeping the value the same, hence you don’t need the ternary.

Is it possible to use a guard clause and a default clause instead?

sunsetMinute = (sunsetMinute < 10 && '0' + sunsetMinute) || sunsetMinute;

Yes it is possible, but it’s busier than it really needs to be.

When using the ternary, I think that I prefer it like this:

sunsetMinute = sunsetMinute >= 10 ? sunsetMinute : '0' + sunsetMinute;

Because that’s saying that the adjustment only occurs if it’s needed.

What about if we only focus on what is being added?

sunsetMinute = (sunsetMinute >= 10 ? "" : "0") + sunsetMinute;

That one is more preferable, as it’s clearly saying that we only prepend a 0 if it’s needed.

1 Like

Thanks for the help, everyone!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.