Search code examples
javascriptswitch-statementeval

Is "eval" the only way to use JS "switch" as an expression?


I found that in JavaScript, switch is always a sentence of instruction and using it as an expression will give an error. So when I have to assign different values to a variable according to different condition, I have to write like this:

switch(true){
    case x<0.1: aVariable = '#f0f0f0';break;
    case x<0.2: aVariable = '#d3eadf';break;
    case x<0.3: aVariable = '#bce1cd';break;
    case x>=0.3: aVariable = '#9cd4b9';break;
}

Or I should use 'eval()' like this:

aVariable = eval("switch(true){"+
    "case x<0.1:'#f0f0f0';break;"+
    "case x<0.2:'#d3eadf';break;"+
    "case x<0.3:'#bce1cd';break;"+
    "case x>=0.3:'#9cd4b9';break;"+
"}");

Is there any other way to use switch as an expression rather than a sentence of instruction so that I can make my code less verbose?


Solution

  • You can use a direct approach with an array and calculate the index when you have values with fixed interval. So according to your values, you need

    value index comment
    ----- ----- ------------------------------------------
     0.0     0  take integer of value * 10 
     0.05    0  see above
     0.1     1  see above
     0.15    1  see above
     0.2     2  see above
     0.25    2  see above
     0.3     3  see above
     0.35    3  covert by condition and a fixed value of 3
     0.40    3  see above
    

    This answer may not look good for four values, but when it comes to more values with fixed intervals, than it is easier to think about an other structure of decision logic.

    function color(x) {
        return ['#f0f0f0', '#d3eadf', '#bce1cd', '#9cd4b9'][x > 0.3 ? 3 : x * 10 | 0];
    }
    var i;
    for (i = 0; i < 0.5; i += 0.05) {
        document.write(i.toFixed(4) + ' ' + color(i) + '<br>');
    }