Complex conditional judgments in JavaScript often lead to confusing code, and a long string of if/else or switch blocks can become bloated.

For example, suppose we have a function that needs to convert the semantics of a phrase based on actual business knowledge, using only an if/else statement with the following structure:

function getTranslation (str) {
	if (str.toLowerCase() === 'stock') {
  	return 'fall in stock';
  } else if (str.toLowerCase() === 'fund') {
  	return 'welfare fund';
	} else if (str.toLowerCase() === 'bond') {
  	return 'short-term liabilities';
	} else if (str.toLowerCase() === 'deposit') {
  	return 'fixed deposit';
	}
  return 'finance';
}
Copy the code

This code is not very readable, and there are repeated toLowerCase() statements. If the switch statement is used:

function getTranslation (str) {
	switch (str.toLowerCase()) {
    case 'stock':
  		return 'fall in stock';
    case 'fund':
  		return 'welfare fund';
    case 'bond':
  		return 'short-term liabilities';
    case 'deposit':
  		return 'fixed deposit';
    default:
  		return 'finance'; }}Copy the code

Even though toLowerCase() was only called once, it still felt less readable, and swtich statements encountered more complex logic and were prone to missing breaks and causing errors.

You can use objects to do this in a more concise way:

function getTranslation (str) {
    const obj = {
      'stock': 'fall in stock'.'fund': 'welfare fund'.'bond': 'short-term liabilities'.'deposit': 'fixed deposit'
    };
    return obj[str.toLowerCase()] ?? 'finance';
}
Copy the code

The last part of line 9 uses the null merge operator (??) To set the default values. Return ‘finance’ if obj[str.tolowerCase ()] is null or undefined (but not 0 or false). This is critical because we might want to legally return 0 or false, for example:

function getTranslation (str) {
    const obj = {
      'true': true.'false': false
    };
    return obj[str.toLowerCase()] ?? 'not boolean';
}
Copy the code

When there is more complex logic that can pass a function as a value to an object’s key and execute the response:

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

Here line 9 uses the optional chain operator (? .). To execute the defined response, otherwise the default string is returned.