DEV Community

AlexCrown1985
AlexCrown1985

Posted on

Alternative to if / else and switch: object literals in JavaScript

Complex conditions in JS have always been a source of redundant code. However, using object literals in JavaScript can save you this problem. Let's see how it works.

An object literal in JavaScript is a comma-separated list of key-value pairs wrapped in curly braces.

Let's say we have a function that takes as input a rhymed phrase in English Cockney slang and returns its value. If you use the if / else construction, the code will look like this:

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

  return "Rhyme not found";
}
Enter fullscreen mode Exit fullscreen mode

It looks so-so. This code is not only difficult to read, but it also uses a repeated call to the toLowerCase () function. To reduce the amount of code, we can use an additional variable or switch construct.

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";
  }
}
Enter fullscreen mode Exit fullscreen mode

This code looks cleaner, but it's not the limit. In addition, in the case of using more complex conditions, you can accidentally skip break and provoke bugs.
We can achieve the same functionality using an object. Here's an example that looks much cleaner:

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";
}
Enter fullscreen mode Exit fullscreen mode

When adding emoji trends charts on emojio.top we use an object whose keys act as conditions and values ​​act as results. Then, using square brackets, we check for the presence of the desired line. Since the resulting string can be null or undefined, we use the Nullish coalescing operator (??). Thus, we get rid of the null value, but do not exclude the case that the result can be zero or false.

function stringToBool(str) {
  const boolStrings = {
    "true": true,
    "false": false,
  };

  return boolStrings[str] ?? "String is not a boolean value";
}
Enter fullscreen mode Exit fullscreen mode

This is a slightly contrived example, but it illustrates how to use ?? helps to avoid bugs.

To organize more complex conditions, you can use functions as property values.

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,
  };

  return actions[action]?.(num1, num2) ?? "Calculation is not recognised";
}
Enter fullscreen mode Exit fullscreen mode

In this code, we select the required function by key, and then call it with two arguments. Since we are using optional chaining, the function will only be called if it exists. Otherwise, the default value will be returned.

Output
Each conventional construction has its own area of ​​application. For object literals in JavaScript, these are long lists of conditions and complex conditions that can be implemented using functions.

Top comments (0)