Comparing numbers and making a calculation I have a piece of javascript I wrote for a recent work project that is essentially taking a deviceorientation event object, taking either the beta value or gamma value of that object and makes a calculation.

While I can't necessarily put my exact code here just in case that breaks any of the agreements I signed, the general idea is as follows. Just a note: this code is already headed for production and I'm not looking for someone to do my work for me. I'm asking this so I can use it for new code in the future. I like to keep functions small and avoid using complex structures like the one below, but my time in this field is still limited and I could not think of a better way to handle this.

The names of functions/variables have been changed to protect the identity of the innocent. I'm also skipping a few of the in between functions as I'm just wondering if there's a cleaner way to handle this calculation.

Code starts with adding an event listener:

window.addEventListener('deviceorientation', doSomeStuff, false);


doSomeStuff eventually makes a call to makeCalculation and passes along the event object:

function doSomeStuff(event){
    // Other stuff happens...
    makeCalculation(event);
}


At this point, I want to make a calculation based on the beta or gamma value of that event object. I have a minimum and maximum range I want stay within, as well as a slight alteration to the calculation when the value is between another range within the min-max range. I will use event.gamma as an example and ignore the logic to determine whether I want to use beta or gamma;

function makeCalculation(e){
    var value;    

    if (Math.round(e.gamma) === 0) {
        value = 0;
    } else if (e.gamma &lt; -2) {
        value = // Some Calculation
    } else if (e.gamma &gt; 2) {
        value = // Some Other Calculation
    } else {
        value = // Yet a different calculation 
    }

    return value;
}


Is there a better way to make number comparisons of this nature without having to creating a nasty looking if/else if block?
Given your conditions, there's no way around the if-else statements. You have to enforce the conditions somehow.

Instead of if-else, another option is a switch statement, but the outcome is essentially the same:

switch (true) {
    case Math.round(e.gamma) === 0:
        value = 0;
        break;
    case e.gamma &lt; -2:
        value = -2;
        break;
    case e.gamma &gt; 2:
        value = 2;
        break;
    default:
        value = 99;
}