background

When doing Code Review these days, I found many if-else/switch statements, which were not particularly elegant. In some logically complex places, it looks bloated and not so easy to read.

Here’s an example:

function getTranslation(rhyme) {
  const lowercasedRhyme = rhyme.toLowerCase();
  if ( lowercasedRhyme === "apples and pears") {
    return "Stairs";
  } else if (lowercasedRhyme === "hampstead heath") {
    return "Teeth";
  } else if (lowercasedRhyme === "loaf of bread") {
    return "Head";
  } else if (lowercasedRhyme === "pork pies") {
    return "Lies";
  } else if (lowercasedRhyme === "whistle and flute") {
    return "Suit";
  }
  return "Rhyme not found";
}
Copy the code

LowercasedRhyme === ‘XXX’; lowercasedRhyme === ‘XXX’;

If it is a switch statement:

function getTranslation(rhyme) {
  switch (rhyme.toLowerCase()) {
    case "apples and pears":
      return "Stairs";
    case "hampstead heath":
      return "Teeth";
    case "loaf of bread":
      return "Head";
    case "pork pies":
      return "Lies";
    case "whistle and flute":
      return "Suit";
    default:
      return "Rhyme not found"; }}Copy the code

It’s better, but it’s still bloated, so we just need to return a value.

It is also easy to miss the break statement and cause errors when you encounter more complex features.

Another way:

function getTranslationMap(rhyme) {
  const rhymes = {
    "apples and pears": "Stairs"."hampstead heath": "Teeth"."loaf of bread": "Head"."pork pies": "Lies"."whistle and flute": "Suit"};return rhymes[rhyme.toLowerCase()] ?? "Rhyme not found";
}
Copy the code

We directly use key-value form to fetch data, and finally use?? The bottom line.

Here?? , is the so-called void merge operator:

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
Copy the code

Unfamiliar friends, you can go to see the document: developer.mozilla.org/en-US/docs/…

If you have more complex logic, you can also do this in appropriate scenarios, such as:

function calculate(num1, num2, action) {
  const actions = {
    add: (a, b) = > a + b,
    subtract: (a, b) = > a - b,
    multiply: (a, b) = > a * b,
    divide: (a, b) = > a / b,
  };

  returnactions[action]? .(num1, num2) ??"Calculation is not recognised";
}
Copy the code

One thing to notice, we’re using both here, right? And?? Operators.

conclusion

The question we are discussing today is subjective, with some personal preference.

Code readability, maintainability, should be something we all need to pay attention to.

That’s all for today, I hope it’s helpful 🙂