Last Updated: February 25, 2016
·
905
· chrisdl

for...in vs. for

Summary: The for...in-loop counts only the used indexes in an array while the "regular" for-loop loops through the entire thing.

Setup:

anArray = [];
anArray[50] = "Fifty";
anArray[100] = "Hundred";
anArray[150] = "Hundred Fifty";


console.log(anArray.length); // 151

Way to count actual used elements efficiently.

var count  = 0;
for (var index in anArray) {

    console.log(index);
    /*
        Loop 1: 50
        Loop 2: 100
        Loop 3: 150
    */

    count++;

    console.log(anArray[index]);
    /*
        Loop 1: "Fifty"
        Loop 2: "Hundred"
        Loop 3: "Hundred Fifty"
    */
}
console.log(count); // 3

4 Responses
Add your response

You could also do it in a more compact way:

var count = 0;
anArray.forEach( function(x, i) { if ( x != null ) count++; } );
over 1 year ago ·

@engineergio If you want compact, the OP's is as terse as it gets:

var i,c=0;for(i in anArray){c++;}
over 1 year ago ·

@passcod nice :)

over 1 year ago ·

@engineergio Is the if so that it works the same in all browers?:

if ( x != null )

@passcod and @engineergio, both of yours are very terse/sexy indeed, but I wanted the tip to be more readable. The key insight here is that the for...in-loop only iterates three times.

over 1 year ago ·