Derek Chan

Staying in the JS Loop with this Neat For-Loop Trick

I happened to discover a unique way of iterating through an array by means of a for-loop that works like Array.prototype.forEach. In fact, it wouldn't surprise me if the function was implemented like how I did.

For those of you who like to get straight to the point, here it is:

let array = [1,2,3,4];
for (let i = 0, a = array[i], len = array.length; i < len; a = array[++i]) console.log(a);

The above code prints out the numbers 1 to 4 inclusively.

Explanation

A for-loop consists of four components: the initialization, condition, final-expression, and body. An in-depth explanation can be found here. The trick here is to initialize multiple variables at once, specifically ones for the counter, array length, and a third variable for what is in the array at the index indicated by the counter. In addition, the final statement has to both increment the counter and set the third variable. This is accomplished in one statement by means of the prefix increment operator. The length variable is there in order to reduce the number of lookups.

Hopefully this might be of use to you!