HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Looking for a better solution than a bunch of switch statements in my JavaScript

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
switchjavascriptstatementsthanbetterlookingbunchforsolution

Problem

I'm calling this function from my html (and in some cases from another function in my JavaScript). These type of switch statements are starting to litter my code. Is there a more elegant solution to these if statements? I wish I could pass a reference to the variables I want to modify. I'm finally asking the question because now I have a situation where if I do it this same way, I'm going to have an ugly switch statement with hundreds of cases which I'm guessing not only looks ugly, but will hurt performance.

function incCriteriaStats(exp){
    switch (exp) {
      case "a":
        numOfA++;
        break;
      case "b":
        numOfB++;
        break;
      case "c":
        numOfC++;
        break;
      case "d":
        numOfD++;
        break;
      case "e":
        numOfE++;
        break;
      case "f":
        numOfF++;
        break;
      case "g":
        numOfG++;
        break;    
    }
|

Solution

Why not use an object to store the values for a, b, c, etc, rather than using separate numOfA, numOfB, etc variables:

var obj = { 
   "a": 0,
   "b": 0,
   "c": 0,
   "d": 0,
   "e": 0,
   "f": 0,
   "g": 0
};


This will allow you to do something nice and simple like this:

function incCriteriaStats(exp){
   if (obj[exp] != null)
       obj[exp]++;
}

Code Snippets

var obj = { 
   "a": 0,
   "b": 0,
   "c": 0,
   "d": 0,
   "e": 0,
   "f": 0,
   "g": 0
};
function incCriteriaStats(exp){
   if (obj[exp] != null)
       obj[exp]++;
}

Context

StackExchange Code Review Q#7385, answer score: 7

Revisions (0)

No revisions yet.