Search code examples
javascriptnullprototypejs

Checking if object not null before accessing property


var how = $('how');
var id = $('myId');
if ((how != null && !how.value.blank()) || myId != null) {
    return true;
} else {
    alert('Error');
}

Is there an easier way to check for not null and checking if the value of that element is blank without having to do both != null and then calling value?


Solution

  • Since null is falsy, a slightly shorter version would be

    if((how && !how.value.blank()) || myId != null) { 
      ...
    }
    

    Note that the above code and your own snippet both assume that if how exists, it will have a property called value, and will throw an exception if this is not the case.