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); // 3Written by Chris
Related protips
4 Responses
You could also do it in a more compact way:
var count = 0;
anArray.forEach( function(x, i) { if ( x != null ) count++; } );@engineergio If you want compact, the OP's is as terse as it gets:
var i,c=0;for(i in anArray){c++;}@passcod nice :)
@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.
Have a fresh tip? Share with Coderwall community!
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside