Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

58
Vistas
Cleaner way and alternative to write if and else with JS checks

What are some alternatives to write cleaner, better, and smarter if/else function?

I am actually trying to convert my code to something more readable.

 const statusComment = () => {
      const isApproved = "🟢";
      const unApproved = "🔴";

      let status;

      // is approved and has comment.
      if (checkApproval && comment) {
        status = `${isApproved}  — ${comment}`;
        // is not approved and has comment.
      } else if (!checkApproval && comment) {
        status = `${unApproved}  — ${comment}`;
        // has comment.
      } else if (comment) {
        status = comment;
        // is approved.
      } else if (checkApproval) {
        status = isApproved;
      } else {
        // is not approved.
        status = unApproved;
      }

      return status;
    };
7 months ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Let's break it down a bit: your string has two parts that are joined by a dash -:

  1. The first part is always present: it depends on the checkApproval boolean value.
  2. The second part is optional and depends on the truthy status of comment.

Also, do note that your third statement is not possible to get to, since comment is always truthy in the first two statements and it's combined with a boolean flag.

Therefore, you can create an array with the compulsory first part with this ternary statement:

const status = [checkApproval ? "🟢" : "🔴"];

For the second optional part, you push into it when comment is truthy:

if (comment) status.push(comment);

Here's your modified code:

const statusComment = () => {
  const status = [checkApproval ? "🟢" : "🔴"];
  if (comment) status.push(comment);

  return status.join(' — ');
};
7 months ago · Juan Pablo Isaza Denunciar

0

Let's make a table based on your existing code:

checkApproval     comment        out
true              true           green - comment
false             true           red - comment
                  true           comment         duplicate/unnecessary?
true                             green
false                            red

So we see that if there is true for checkApproval, it's green, and red otherwise.

Let's make that right now:

const status = `${checkApproval ? "🟢" : "🔴"}`;

And if there's a comment, there is a dash followed by the comment. This we can represent too:

const status = `${checkApproval ? "🟢" : "🔴"}${comment ? " - " + comment : ""}`;

If there is no comment, nothing is added after.

Then we can just return status normally.

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos