2

Does make sense to check if the length of the array is not equal to 0 before of to do the loop?

var arr = [1,2,3];
if (arr.length !== 0) {
    // do loop
}
0

3 Answers 3

5

In the general case it doesn't make sense. For a foreach, for, or while loop, the loop condition will prevent the loop executing anyway, so your check is redundant.

var arr = [];
for (var loopCounter = 0; loopCounter < arr.length; loopCounter++)
{
   // This loop will never be entered.
} 

foreach (var element in arr)
{
   // This loop will never be entered.
}

var loopCounter = 0;
while (loopCounter < arr.length)
{
   // This loop will never be entered.
   loopCounter++;
} 

However, the only time it is important is if you are using a do...while loop. In this scenario, the loop executes, and then you check your loop-condition (when it is too late). It's likely that your code would have thrown an exception inside the loop in this case, as demonstrated in the following code.

var arr = [];
var loopCounter = 0;
do 
{ 
   someMethod(arr[loopCounter]); // This will throw an error
   loopCounter++;
} 
while(loopCounter < arr.length);
Sign up to request clarification or add additional context in comments.

Comments

1

No, the check is unnecessary. If the array has zero elements, the loop will execute zero times (assuming it is written correctly).

If the array could be null, then checking for that would be valid, e.g.

if(arr !== null)
{
    // loop
}

Comments

1

Well, it depends on the loop. If it's of the form:

for (i = 0; i < arr.length; i++) {
    do_something_with (arr[i]);
}

then, no, the if is superfluous, the for loop body will not execute in this case.

However, if you've done something like (and this seems likely given that you mention a do loop, although you may have actually meant "do the loop", so it's hard to say):

i = 0;
do {
    do_something_with (arr[i]);
    i++;
while (i < arr.length);

then, yes, you'll need it to avoid the problem of using arr[0] if no such beast exists.

But I would consider that second case (check-after) "broken" since the while () {} or for () {} variants (check-before) would be more natural in that case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.