Writing complex conditions in JavaScript always has the potential to create some pretty messy code, bloated with long lists of if/else statements or switches. So how do you optimize a lot of if/else or switch code? Also avoid excessive use of if/else or switch. Object literals can help you write easy-to-read code, and this article will share them with you.
For example, suppose you have a function that needs to get the read of the input comparison operator based on that operator. Using the if/else statement, it looks like this:
The examples in this article are illustrative only and may not be optimal.
Function getComparisonTitle(strOperator) {if (strOperator === ">") {return ">"; } else if (strOperator === ">=") {return ">="; } else if (strOperator === "<") {return "<"; } else if (strOperator === "<=") {return "<="; } else {return "equal "; }}Copy the code
The above code looks bloated and unreadable. With switch, it could look like this:
function getComparisonTitle(strOperator) { let title = ""; Switch (strOperator) {case ">": title = ">"; break; Case ">=": title ="; break; Case "<": title = "<"; break; Case "<=": title =" <="; break; Default: title = "= "; break; } return title; }Copy the code
The code looks slightly better than before, but the Switch is bug prone and the code is still not very readable.
To optimize
The above can be done using an object structure as follows:
The function getComparisonTitle (strOperator) {const operators = {" > ":" more than ", "> =" : "greater than or equal to", "<" : "less than", "< =" : "less than or equal to", "= =" : "Equal to ",}; return operators[strOperator]; }Copy the code
Using objects makes code look more readable and concise. During the project, especially with the Switch, it is recommended to use object literals for optimization.
In general, different methods can be called in a project depending on the situation, and the same method can be used. Here is a simple example:
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 typeof actions[action] === "function" ? Actions [action](num1, num2) : "action undefined "; }Copy the code
The above functions perform simple operations.