2

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);
                }
            }
Community
  • 1
  • 1
Goose
  • 4,243
  • 3
  • 36
  • 75
  • do you understand how short circuit statements work? Your foo is undefined/null so it has no indexed children. you'd be better off short-circuiting that if statement to `if (foo && foo[0])` no need to "typeof" foo[0] tests if it is null/undefined, if not returns true if it is null returns false... unless foo[0] is a boolean, then yea you might want to check specifically if it doesn't equal undefined/null – Mike Jun 22 '15 at 14:35

3 Answers3

8

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 */
Oriol
  • 225,583
  • 46
  • 371
  • 457
  • I'm sure foo is not null in this case, but I will apply this fix anyway to see if it works. – Goose Jun 22 '15 at 14:18
  • I referenced your answer in mine. `:D` – Praveen Kumar Purushothaman Jun 22 '15 at 14:20
  • Wow, nevermind, this worked. Yet I'm still sure that foo was not null. Why did this prevent foo[0] from throwing an error if foo wasn't null and it was a redundant check? – Goose Jun 22 '15 at 14:20
  • I will mark this as correct, however, I still don't understand how it fixes the problem, because I'm checking and in the breaking loop, foo is not null anyways. Please explain if you have a moment and are able to. – Goose Jun 22 '15 at 14:23
  • @Goose Are you sure? The errors says it clear that `foo` is `null`. – Oriol Jun 22 '15 at 14:23
  • Strange enough, it passes the if statement, because foo[0] was set, because it hasn't been redefined at the start of the loop, which is acceptable behavior for how I'm using it. Not sure why it failed in the first place, or why it's passing after adding that. – Goose Jun 22 '15 at 14:29
  • 1
    If you want to save keystrokes, arrays evaluate to `true` so you can just write `foo && typeof foo[0]...`. Just be aware in some cases this is slightly more permissive than checking `== null`. – Katana314 Jun 22 '15 at 14:30
3
if (typeof(foo && foo[0]) !== 'undefined') 
{ 
   // I want to get here
}
Milan Rakos
  • 1,455
  • 15
  • 22
-1

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"

Griva
  • 1,263
  • 16
  • 33
  • 1
    Actually, that's what I had when I posted the question. I have restored it now that I realize that's not what was causing the issue. – Goose Jun 22 '15 at 14:28
  • Yes, too late updated ;) but javascript is strange {} + {} = NaN, [] + [] = "" and {} + [] = 0 so remember this xD – Griva Jun 22 '15 at 14:36