jQuery length of object to determine existence gives error? The following jQuery in my module gives an error that breaks LOTS of other javascript on other modules on the page. I want to know why. Why?

 var pid = $('input[name="product_id"]').attr('value');
 if ( pid.length )
   // do stuff                              


But this works fine:

var pid = $('input[name="product_id"]').attr('value');
if ( typeof(pid) !== 'undefined' )
  // this works fine


I've been using the first example for years in other environments to test for the existence of an object and it always works. What am I missing?

TIA.
if (pid.length)


causes a reference error in your script if pid is undefined.  So, if you don't know that pid exists ahead of time, then you have to check to see if that object is valid before trying to reference properties on it.

FYI, you could probably just use:

if (pid)


because that would protect you from pid being undefined or an empty string.



It has been raised in comments that maybe you're actually just trying to test for the existence of a DOM object, not the attribute.  If that's the case, then you should just be doing this:

if ($('input[name="product_id"]').length)


which tells you if the selector matched any DOM objects.