Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I check for not equal in a JavaScript switch statement?

Tags:

javascript

var t = "TEST";
switch(t){
    case !"TEST": /* <- does not work. Can you check if t does NOT contain a string? */
        alert("t != TEST");
    break;
}

Can you do this with a switch statement?

like image 316
subZero Avatar asked Oct 28 '13 13:10

subZero


People also ask

Does switch use == or ===?

Yes, switch "[uses] the strict comparison, === ".

Can we use condition in switch case JavaScript?

If you want pass any value in switch statement and then apply condition on that passing value and evaluate statement then you have to write switch statement under an function and pass parameter in that function and then pass true in switch expression like the below example.

Which switch statement is used if no match is found?

Use break to prevent the code from running into the next case automatically. The default statement is used if no match is found.


2 Answers

you can also do this:

var str = "TEST";

switch (true) {
    case (str !== "TEST") :
        alert("str !== TEST");
        break;
    case (str === null) :
        alert("str is null");
        break;
    default:
        alert("default trigger");
}
like image 102
jcamelis Avatar answered Oct 14 '22 09:10

jcamelis


You can use if. If you prefer switch, use a 'default' case and an if condition there like

default:
    if(n == -1){
        //Your code
    }
    break;
like image 25
Marikkani Chelladurai Avatar answered Oct 14 '22 08:10

Marikkani Chelladurai