

Content for each of these three components is optional, which means that the following is the most minimal for-loop possible : for ( ) somewhere inside that for-loop to get it to stop running. These three components are seperated from each other by a symbol. the afterthought : performed every time after the loop block is executed.the condition : checks a condition every time before the loop block is executed, and quits the loop if false.the initialization : executed before the look block is executed the first time.Option 1 : The traditional for-loop The basicsĪ traditional for-loop has three components : If you're dealing with sparse arrays (e.g., the array has 15 elements in total but their indexes are strewn across the range 0 to 150,000 for some reason, and so the length is 150,001), and if you use appropriate safeguards like hasOwnProperty and checking the property name is really numeric (see link above), for.in can be a perfectly reasonable way to avoid lots of unnecessary loops, since only the populated indexes will be enumerated. But it's not a safe assumption that you can just use it for that. Since arrays are objects, and their only enumerable properties by default are the indexes, it mostly seems to sort of work in a bland deployment. Specifically, for.in loops through the enumerable property names of an object (not the indexes of an array). You'll see people saying to (in fact, briefly there was an answer here saying that), but for.in does not do what many people think it does (it does something even more useful!). do something with `item` (`this` is the same as it was outside)ĭon't use for.in for this (or if you do, do it with proper safeguards). The third option below, jQuery.each, isn't in it though.) var new_array = array.(Update: My other answer here lays out the non-jQuery options much more thoroughly.


The thisArg (optional) - value for the callback function which will be used as its this value. Similarly, filter will show the array in this. 2 JavaScript array filter and find Note: find will only give one item which is at the first.

