Javascript "Cannot read property 'length' of undefined" when checking a variable's length -


i'm building node scraper uses cheerio parse dom. more or vanilla javascript question though. @ 1 part of scrape, i'm loading content variable, checking variable's length, so:

    var thehref = $(obj.mainimg_select).attr('href');         if(thehref.length){            // stuff         }else{           // other stuff         } 

this works fine, until came across url $(obj.mainimg_select).attr('href') didn't exist. assumed thehref.length check account , skip through else: other stuff statement, instead got:

typeerror: cannot read property 'length' of undefined

what doing wrong here , how can fix this?

you can check thehref defined checking against undefined.

if (undefined !== thehref && thehref.length) {     // `thehref` not undefined , has truthy property _length_     // stuff } else {     // other stuff } 

if want protect against falsey values null check thehref truthy, little shorter

if (thehref && thehref.length) {     // `thehref` truthy , has truthy property _length_ } 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -