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

javascript

Solution

You can check that `theHref` is defined by checking against undefined.

if (undefined !== theHref && theHref.length) {
    // `theHref` is not undefined and has truthy property _length_
    // do stuff
} else {
    // do other stuff
}

If you want to also protect yourself against falsey values like `null` then check `theHref` is truthy, which is a little shorter

if (theHref && theHref.length) {
    // `theHref` is truthy and has truthy property _length_
}

Problem

I'm building a `node` scraper that uses `cheerio` to parse the `DOM`. This is more or a vanilla javascript question though. At one part of my scrape, I'm loading some content into a variable, then checking the variable's `length`, like so: ``` var theHref = $(obj.mainImg_select).attr('href'); if (theHref.length){ // do stuff } else { // do other stuff } ``` This works just fine, until I came across a url for which `$(obj.mainImg_select).attr('href')` didn't exist. I assumed that my `theHref.length` check would account for this and skip through to the `else: do other stuff` statement, but instead I got: `TypeError: Cannot read property 'length' of undefined` What am I doing wrong here and how can I fix this?

Original source

Related problems