Check the length of an array before of to do a loop in JavaScript - Stack Overflow

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

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
}

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
}
Share Improve this question edited Oct 25, 2012 at 8:44 asked Oct 25, 2012 at 8:37 user1243746user1243746 0
Add a ment  | 

3 Answers 3

Reset to default 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);

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
}

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744849737a4597056.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信