[thelist] Using for loops with a twist

Christian Heilmann codepo8 at gmail.com
Mon Apr 2 17:49:03 CDT 2007


<tip type="JavaScript for loops" author="Chris Heilmann">
In case you didn't know: The condition part of a JavaScript for loop
can be any condition, it does not need to compare the iterator. This
allows you for example to loop through an array without reading the
length:

var arr = [1,2,0,4,5];
for(var i=0;arr[i];i++){
  alert(arr[i]);
}

However, as 0 is falsy, you need to check properly:

var arr = [1,2,0,4,5];
for(var i=0;arr[i]!==undefined;i++){
  alert(arr[i]);
}

More at http://www.wait-till-i.com/index.php?p=420
</tip>

-- 
Chris Heilmann
Book: http://www.beginningjavascript.com
Blog: http://www.wait-till-i.com
Writing: http://icant.co.uk/



More information about the thelist mailing list