Opinions about code clarity on specific example - ternary operator vs if/else statements

Hi there!

I would like to ask a question that pertains mostly to style (I think).

Which of the two bits of code would you favor, and why?

Maybe it’s not that big of a deal, but I came up with this logic and was trying to decide which solution feels nicer regarding code repetition and clarity.

I tend to favor the first one.

(please, look below for context. this is a React exercise from Angela Yu’s Web Dev Bootcamp on Udemy)

#1

const salutation = time < 12 ? "Good morning" : time < 18 ? "Good afternoon" : "Good evening";
const customStyle = time < 12 ? { color: "red" } : time < 18 ? { color: "green" } : { color: "blue" };

#2

let salutation = "";
const customStyle = {};

if (time < 12) {
  salutation = "Good morning";
  customStyle.color = "red";
} else if (time < 18) {
  salutation = "Good afternoon";
  customStyle.color = "green";
} else {
  salutation = "Good evening";
  customStyle.color = "blue";
}

Original context:

 //Show a single h1 that says "Good morning" if between midnight and 12PM.
 //or "Good Afternoon" if between 12PM and 6PM.
//or "Good evening" if between 6PM and midnight.
//Apply the "heading" style in the styles.css
//Dynamically change the color of the h1 using inline css styles.
//Morning = red, Afternoon = green, Night = blue.

import React from "react";
import ReactDOM from "react-dom";

const date = new Date();
const time = date.getHours();

// const salutation =
//   time < 12 ? "Good morning" : time < 18 ? "Good afternoon" : "Good evening";
// const customStyle =
//   time < 12 ? { color: "red" } : time < 18 ? { color: "green" } : { color: "blue" }; 

let salutation = "";
const customStyle = {};

if (time < 12) {
  salutation = "Good morning";
  customStyle.color = "red";
} else if (time < 18) {
  salutation = "Good afternoon";
  customStyle.color = "green";
} else {
  salutation = "Good evening";
  customStyle.color = "blue";
}

For some reason, I’m having some difficulty in pasting here the final lines of code with the JSX implementation using the ReactDOM.render() method.

Nested ternaries are horribly difficult to read, and are almost universally disliked, so imo not the first one.

There are specific reasons you might use one (for example, with React, it you want the equivalent of if/elseif within JSX code there isn’t a choice), but given the choice if/else is miles easier to read

1 Like

Re the JSX not rendering: you need to put code in code blocks. The forum allows markdown for formatting posts, and markdown allows HTML elements. So if you enter something that looks like HTML outside of a code block, the forum software will think you’re trying to add some stylistic HTML markup to your post.

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

Between nested ternary and if statement, I vote for if-statement.

Personally I would write it like this (but it’s just preference)

let salutation = 'Good Evening';
let customStyle= { color: 'blue' };

if (time < 12) { ... }
else if (time < 18) { ... }

If we’re not tied to that structure, I’d like write it something like this (again, all preference):

// maybe come up with better variable and function names though ;)
const getTimeBasedPersonalization = (time) => {
  // This part makes it obvious to teammates (and future-you) what the "configurable" pieces of this function are
  const morningCutoff = 12;
  const afternoonCutoff = 18;

  if (time < morningCutoff) {
    return {
      salutation: '...',
      customStyle {
        color: '...'
      }
    };
  }
  if (time < afternoonCutoff) {
    return { ... };
  }

  return { ... };
}

const timeBasedPersonalization = getTimeBasedPersonalization(time);
1 Like

Thanks Dan! Good to know what the common appreciation is regarding this topic! :+1: :+1:

And thank you also for the explanation about using the code blocks :wink:

Hi Jeff, thank you for taking the time to answer!

I can see how using a function adds to clarity. I guess that is something that can be better-learned coding in a team. I’ll take your tips with me :wink:

:+1: :+1:

It truly depends on the context.

If the logic is simple and inside an inline phtml, for instance, then it is actually preferred in overall legibility. Especially when inside large html code blocks.
ie:

// set to black or do nothing
<?= echo ( $isblack ) ? 'style="color:  #000"' : '' ?>

over

 <?php
       // set to black or do nothing
       if ( $isblack ) { 
          echo 'style="color:  #000"'; 
       }
 ?>

This is not a hard and fast rule though. I’ve also see well formatted chained and ternary expressions in well managed, professional code bases as well as horribly formatted if/else statement blocks.

A soft rule is if it’s a very simple one liner inside more complex code, go for ternary.

If it’s a significant block of code that has multiple levels of items going on, go for if else.

Always remember, a little indentation does wonders for readability as well as intelligent, descriptive namespaces and comments.

Not to mention, it is much faster to write ternary rather than fumble with if () { and matching brackets.

1 Like

Thanks for your reply!

I guess I will develop a feeling and/or have a stronger opinion through exposure to pro code.

cheers!

Nested ternaries on one line are horrendous, never use them. When you lay them out properly, they can be handy:

const salutation = 
    time < 12 ? "Good morning" 
  : time < 18 ? "Good afternoon" 
  : "Good evening";

You can see how you could add more conditions to the list and how it follows the structure of if/else. However, I really only recommend this sort of thing for really low-level “truth-table” type code, and usually only in a language like C. In higher-level code like (most) javascript, you’ll be better off with if/else every time.

BTW, don’t try this in PHP, it got the operator wrong. At one time it would return wrong results, but now it simply won’t let you nest without a whole lot of parentheses.

Also it’ll drive your code formatter nuts, and you’ll have to disable it for that block (if it even lets you).

Even in C I’m super picky about when I use nested ternaries. The use cases that come to mind are

  1. Function calls. If there are only a few variations of the arguments I’ll use in the situation, it’s not worth separate if clauses.
  2. Small inline helper functions. For me, these are ‘write and forget’ code where the name atd a bit of documentation expains the use and the logic won’t need to be changed.
  3. Parameters. Often parameters defined by function arguments only have a few variations, so it’s easier to make them const with nested ternaries.