Search code examples
javascriptswitch-statement

Processing switch cases


How can I do something like this with a switch statement:

String.prototype.startsWith = function( str ){
    return ( this.indexOf( str ) === 0 );
}

switch( myVar ) {
    case myVar.startsWith( 'product' ):
        // do something 
        break;
}

This is the equivalent of:

if ( myVar.startsWith( 'product' )) {}

Solution

  • You can do it, but it's not a logical use of the switch command:

    String.prototype.startsWith = function( str ){
        return ( this.indexOf( str ) === 0 );
    };
    
    var myVar = 'product 42';
    
    switch (true) {
        case myVar.startsWith( 'product' ):
            alert(1); // do something
            break;
    }