jQuery/Json – Cannot convert 'data' to object-Collection of common programming errors

I’ve a simple ajax/json request with jQuery:

$.ajax({
              type: "POST",
              url: "/some-json-url",
              data: "score=" + 1,
              dataType: 'json',
              success: function(data){
                if(data.msg){ 
                    alert(data.msg);
                }
             }
        });

However, if the msg is not set, I gen an error (looking through Opera Dragonfly):

Unhandled Error: Cannot convert ‘data’ to object

How can I check if it exists or not… in a valid way?

  1. If the problem is with data being null then you can check it like so:

    if(data && data.msg){
        //...
    }
    

    or if you have multiple properties, either like this:

    if(data){
        if(data.msg){
            //...
        }
    }
    

    or return early:

    if(!data)
        return;
    
    if(data.msg){
        //...
    }