switch...case statement

Discussion in 'JavaScript' started by camjohnson95, Dec 20, 2009.

  1. #1
    I was recently looking for the equivalent of the 'SELECT CASE' vb block and stumbled upon javascripts switch,case...
    e.g:
    
    switch(document.getElementById("div1").style.color) {
        case "red": color = "255,0,0"; break;
        case "green": color = "0,255,0"; break;
        case "blue": color = "0,0,255"; break;
        default: color = "unknown"; break;
    }
    
    Code (markup):
    which is the equivalent of:
    
    if(document.getElementById("div1").style.color) color="255,0,0";
    else if(document.getElementById("div1").style.color) color="0,255,0";
    else if(document.getElementById("div1").style.color) color="0,0,255";
    else color="unknown";
    
    Code (markup):
    I don't see this used very much, is there any reason behind that? Is it usable in all javascript versions? And how would you use operators such as > or < with it, or 'AND' (&&) and 'OR' (||)?
     
    camjohnson95, Dec 20, 2009 IP