DEV Community

Cover image for Alternative to if / else and switch: object literals in JavaScript
Abdessamad Bensaad
Abdessamad Bensaad

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 password and returns its value. If you use the if / else construction, the code will look like this:

function getPassword(password) {
  if (password.toLowerCase() === "password1234") {
    return "Facebook Password";
  } else if (password.toLowerCase() === "1234Password") {
    return "Instagram Password";
  } else if (password.toLowerCase() === "!pass1234") {
    return "Twitter Password";
  } else if (password.toLowerCase() === "helloworld1234") {
    return "Github Password";
  }
  return "password 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 getPassword(password) {
  switch (password.toLowerCase()) {
    case "password1234":
      return "Facebook Password";
    case "1234Password":
      return "Instagram Password";
    case "!pass1234":
      return "Twitter Password";
    case "helloworld1234":
      return "Github Password";
    default:
      return "password 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 the break and provoke bugs.

Alternative

We can achieve the same functionality using an object. Here's an example that looks much cleaner:

function getPassword(password) {
  const passwords = {
    "password1234": "Facebook Password",
    "1234Password": "Instagram Password",
    "!pass1234": "Twitter Password",
    "helloworld1234": "Github Password",
  };

  return passwords[password.toLowerCase()] ?? "password not found";
}
Enter fullscreen mode Exit fullscreen mode

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 would get rid of the null value, but do not exclude the case that the result can be zero or false.


/**
 * 
 * @param string 
 * @returns boolean
 */

function stringToBool(string) {
  const checkString = {
    true: true,
    false: false,
  };

  return checkString[string] ?? "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.

Complex logic

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 (4)

Collapse
 
phlash profile image
Phil Ashby

Nice use of lookup table(s) to avoid logic, and applicable to pretty much all languages now (even C++!) I would be interested to know the performance impact of the hash-table lookup vs repeated string compares, since someone will undoubtedly put this at the bottom of a triple nested loop or in a recursive parser... :)

Collapse
 
ryanatk profile image
ryan atkinson

Back in the days of JSPerf, the object literal lookup was always faster. The difference grows larger as you add more lines of "if" checks.

It's also a helpful & popular pattern to declare your string constants in an all-caps "constant" name (so const passwords would be const PASSWORDS) to consolidate (as opposed to mixing them throughout lines of an if/else statement) and make them easily recognizable. Then the lookup would read PASSWORDS[password.toLowerCase()]. Definitely not a "rule", but helpful to the reader.

Collapse
 
billionaire9 profile image
Anuwong Mongkudkornburee

very good ideas!

Collapse
 
b3ns44d profile image
Abdessamad Bensaad

Yeaah!!