Alternative to if / else and switch: object literals in JavaScript
Tags: javascript
Published: 2021-04-26 12:59:34

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:

```js
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";
}

```

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.

```js
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";
  }
}
```

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:

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

  return passwords[password.toLowerCase()] ?? "password not found";
}
```

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.

```js

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

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

  return checkString[string] ?? "String is not a boolean value";
}
```

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.

```js
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";
}
```

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.