javascript switch with multiple variables in case

This feels like a silly question but I can’t get it to work:

I am building an event handler that I want to trigger two different outcomes if the user presses "enter" or "shift Enter"

I have this code


         switch(e){
            case (e.keyCode == 13 && !e.shiftKey):
                console.log("Enter")
                break;
            case (e.keyCode == 13 && e.shiftKey):
                console.log("Enter&Shift")
                break;
            default:
                console.log(`Sorry, we are out of it.`);
        }

but something is not working because it always go to default…despite the fact that e.keyValue is actually 13 and e.shiftKey is true…so I am passing the event correctly.

It’s the switch that is wrongly built.

>Solution :

You shouldn’t use a switch statement for this, but regular if and else statements.

if (e.keyCode == 13 && !e.shiftKey) {
    console.log("Enter");
} else if (e.keyCode == 13 && e.shiftKey) {
    console.log("Enter&Shift");
} else {
    console.log(`Sorry, we are out of it.`);
}

Leave a Reply