JavaScript Simplified: Using Objects for Conditional Logic

In JavaScript, we often use if...else if...else chain to handle conditions. But, there is a cleaner way to write this code, objects. For example, look at the following code: for (tab in issueElems) {   if (tab === "open") {     openIssues.innerHTML = "";     openCount.className = "loading loading-spinner loading-xs text-info";     showSpinner(searchSpinner, searchSpinnerText, openIssuesSpinner);   }   else if (tab === "closed") {     closedIssues.innerHTML = "";     closedCount.className = "loading loading-spinner loading-xs text-info";     showSpinner(searchSpinner, searchSpinnerText, closedIssuesSpinner);   }   else {     allIssues.innerHTML = "";     allCount.className = "loading loading-spinner loading-xs text-info";     showSpinner(searchSpinner, searchSpinnerText, allIssuesSpinner);   } } Now, if we define an object like the following beforehand: let issueElems = {   all: {     count: allIssuesCount,     issues: allIssues,     spinner: allIssuesSpinner,   },   open: {     count: openIssuesCount,     issues: openIssues,     spinner: openIssuesSpinner,     tab: openTab,   },   closed: {     count: closedIssuesCount,     issues: closedIssues,     spinner: closedIssuesSpinner,     tab: closedTab,   }, }; The code becomes as simple as this: for (tab in issueElems) {   let c = issueElems[tab];   c.issues.innerHTML = "";   c.count.className = "loading loading-spinner loading-xs text-info";   showSpinner(searchSpinner, searchSpinnerText, c.spinner); } There is also switch...case, but it works in a very absurd way. If you don't add break to case clauses, it keeps going to the next case clause. It starts with the first matching case clause and continues until the break statement is encountered. That's why objects are the best way to handle this matter. What do you use? Share your ideas!

To view or add a comment, sign in

Explore content categories