1
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?

trincot
  • 317,000
  • 35
  • 244
  • 286
uraza
  • 907
  • 4
  • 12
  • 22
  • What is `how` and is `$` jQuery? Also, where does the prototype come into play? – nils Aug 29 '16 at 07:32
  • Since the question is tagged prototype (and since the selectors aren't valid jQuery selector), I think it's safe to assume that `$` is prototype, and that's how it comes into play. – David Hedlund Aug 29 '16 at 07:33
  • @DavidHedlund: Except that the [tag:propotype] tag is not relevant for this question. If he's using [tag:prototypejs], the OP should use that tag. – Cerbrus Aug 29 '16 at 07:35
  • @Cerbrus: Fair enough, the tag should've been prototypejs. I still think the answers to *is `$` jQuery* and *where does prototype come into play* are rather obvious in the question at hand. – David Hedlund Aug 29 '16 at 07:43

1 Answers1

2

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.

David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • Why to check myId!=null we can do it directly myId as well like: if((how && !how.value.blank()) || myId) { } Just for curiosity.... – Ankur Verma Aug 29 '16 at 07:35
  • 1
    @ankurverma: Mainly because I only addressed the specific part of the question that OP asked for, leaving the rest of the snippet intact. I also didn't want to make any assumptions that weren't already implicit in the condition. We know that `how` is expected to be an object because we proceed to access `how.value` if it exists. We don't, in the same way, know which values are valid for `myId`. By variable name alone, it is conceivable that it is an integer, and that `0` is a valid non-null value. – David Hedlund Aug 29 '16 at 07:41
  • Having said that, I agree that we can be fairly certain your solution would suffice, as we know `myId` is defined as the value of `$('myId')`, which means it is probably a DOM node or null. – David Hedlund Aug 29 '16 at 07:41
  • Thanks @DavidHedlund for your explanation :) – Ankur Verma Aug 29 '16 at 07:45