0

A couple days ago, on a site that I'm the only author on, I added this code to a script:

if (PowerArray[0][0].length < 1);
{
    return false;
}

and everything worked fine. When PowerArray[0][0] was "70", the script ran. When PowerArray was empty, the script didn't run past the above quoted line. This is no longer true. For the life of me, I can't figure it out. I tested with variants of the code, like below:

if (PowerArray[0][0].length < 1);
{
    alert(PowerArray[0][0].length);
    return false;
}

and set PowerArray[0][0] = "70". When I run the code, I get an alert with "2" in the text. This is the only place that I have an alert in the script. What's going on here, and how do I fix it?

Note: The expected behavior is, of course, no alert, because "70" has a length of 2, and shouldn't trigger the truth of the if.

Edit: 1) Yes, the False in the first block was a typo. It's been corrected. 2) The expected behavior was for it to stop processing if (and only if) PowerArray[0][0].length was 0. 3) I had previously initialized PowerArray as an empty array, and then copied an array (which had the potential to be empty) into it.

Farfromunique
  • 447
  • 1
  • 6
  • 15

4 Answers4

4

You should remove semicolon from if statement, it terminates your statement there. And yes, when your PowerArray is empty, PowerArray[0][0] will throw an undefined error, So should put a null check for that as well.

Rails Guy
  • 3,836
  • 1
  • 20
  • 18
  • it is a logical error, but not the reason for the later scripts not running when `PowerArray ` is empty – Arun P Johny Jul 16 '13 at 04:49
  • @ArunPJohny but it is why the asker is observing 70 in his array. Upvoting your answer, however, because that's the next issue OP will encounter. – John Dvorak Jul 16 '13 at 04:50
3

when PowerArray is empty PowerArray[0] gives undefined then you will get an error for PowerArray[0][0] saying TypeError: Cannot read property '0' of undefined that is why the script is nor running after that line

if (PowerArray && PowerArray[0] && PowerArray[0][0] && PowerArray[0][0].length < 1)
{
    return false;
}
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

try this

   if (PowerArray[0]) {
            if (PowerArray[0][0].length < 1) {
                return False;
            }
        }
iJade
  • 23,144
  • 56
  • 154
  • 243
  • apart from the extra semicolon you didn't fix... if the value is falsy, its length (if it has any) would be zero. – John Dvorak Jul 16 '13 at 04:49
0

I think the semicolon after the if is the issue. I would also check if PowerArray is a valid 2D array implementation. Check this link for ideas How can I create a two dimensional array in JavaScript?

Start by changing it to this if (PowerArray[0][0].length < 1)

Community
  • 1
  • 1
TGH
  • 38,769
  • 12
  • 102
  • 135