Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 395
JVG Avatar asked Jul 11 '13 00:07

JVG


2 Answers

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_ } 
like image 137
Paul S. Avatar answered Oct 07 '22 15:10

Paul S.


Why?

You asked why it happens, let's see:

The official language specificaion dictates a call to the internal [[GetValue]] method. Your .attr returns undefined and you're trying to access its length.

If Type(V) is not Reference, return V.

This is true, since undefined is not a reference (alongside null, number, string and boolean)

Let base be the result of calling GetBase(V).

This gets the undefined part of myVar.length .

If IsUnresolvableReference(V), throw a ReferenceError exception.

This is not true, since it is resolvable and it resolves to undefined.

If IsPropertyReference(V), then

This happens since it's a property reference with the . syntax.

Now it tries to convert undefined to a function which results in a TypeError.

like image 36
Benjamin Gruenbaum Avatar answered Oct 07 '22 15:10

Benjamin Gruenbaum