Goose
Goose

Reputation: 4821

While using typeof, getting "Cannot read property '0' of null"

What I want

I'm trying to use typeof to check if an array element exists. The reason is to prevent Cannot read property '0' of null error. However, just trying to check if the element exists causes the error.

What I've tried

if (typeof foo[0] !== 'undefined') 
{ 
    // I want to get here
}

and

if (typeof(foo[0]) !== 'undefined') 
{ 
    // I want to get here
}

This is part of a loop, and the first four iterations work, the fifth is not suppose to work, and the sixth is suppose to work. However, it is failing on the fifth loop. I can't write an exception, because the input can change which iterations of the loop are suppose to work and which are not suppose to work.

I believe this is the correct way and I should not be receiving this behavior based off these stackoverflow answers.

Check if an array item is set in JS

Checking if a key exists in a JavaScript object?

JavaScript isset() equivalent

How to check if a multidimensional array item is set in JS?

I thought the point was typeof is that you can check if an element is set before attempting to use it and throwing yourself an error. Other users seem to be able to use accomplish this. I'm guessing I'm doing something different. How do I check if the array index is set without failing the script because I'm looking at an array index that is not set.

Code in more context

Shouldn't be needed, but just incase.

            for (templ_i=0; templ_i<number_of_fields; templ_i++)
            {
                // Font size
                if (d['font_size_group'][templ_i]['font_size'])
                {
                    size_re = new RegExp('"text_' + line + '" font-size="\\d+(\\.[0-9]+)?"', 'g');
                    current_line = svg_template.match(size_re);
                    size_re = new RegExp('[^_"]\\d+(\\.[0-9]+)?', 'g');
                    if (typeof current_line[0] !== 'undefined') { current_font_size = current_line[0].match(size_re); }
                    console.log(current_font_size);
                }
            }

Upvotes: 4

Views: 6601

Answers (3)

Milan Rakos
Milan Rakos

Reputation: 1763

if (typeof(foo && foo[0]) !== 'undefined') 
{ 
   // I want to get here
}

Upvotes: 3

Griva
Griva

Reputation: 1738

typeof return 'string'.

If you want use typeof - use it correct:

if (typeof foo[something] != 'undefined') 
{
    // Now you can get foo[something]
}

Important

a = null;
typeof a

will return "object"

Upvotes: -1

Oriol
Oriol

Reputation: 288100

typeof foo[0] does this:

  • Evaluates foo[0]
  • Returns a string with the name of its type

However, if foo is null, foo[0] will throw.

So you can use

foo != null                  /* Filter out undefined and null */
&&
typeof foo[0] != 'undefined' /* Check the type of the property */

Upvotes: 9

Related Questions