andrew
andrew

Reputation: 9583

How to check if switch subject is object?

My Ajax response could be a json object, bool or various string values

Can I check if it was an object in a switch statement?

$.post('url',{some:'data'},function(response){
   switch (response){
   case true:
     console.log('is true');
     break;
   case false:
     console.log('is false');
     break;
   case 'success':
     console.log('is success');
     break;
   case typeof this === 'object' // thought I'd try this but it didn't work.
     console.log('is object');
     break;
   }
});

Upvotes: 1

Views: 149

Answers (2)

Barmar
Barmar

Reputation: 781751

switch performs an equality comparison between the argument and the case expressions. So case typeof this === 'object' calculates the value of typeof this === 'object', which will be either true or false depending on what this is (it will be window in your callback), and compares that to response. It won't test the type of response. If you want to perform a switch on the type of response, use that as the argument.

Try:

switch (typeof response) {
case 'boolean':
    if (response) {
        console.log('is true');
    } else {
        console.log('is false');
    }
    break;
case 'string':
    if (response == 'success') {
        console.log('is success');
    } else {
        // do something
    }
    break;
case 'object':
    console.log('is object');
    break;
}

More generally, switch should be used when you want to do a series of equality tests on the same value. You can't mix equality and type tests in the same switch; you need to use switch for one, if for the other.

Upvotes: 5

user1736947
user1736947

Reputation: 192

Have a default case :

default : 
     if(typeof response === 'object'){ // thought I'd try this but it didn't work.
     console.log('is object');
     }
     break;

Upvotes: 0

Related Questions