Sunday, September 15, 2024

Getting Fancy with the JavaScript For Loop

Getting Fancy with the JavaScript For Loop

Of all the loop types in JavaScript, the for loop is arguably the most versatile. It’s concise, easy to use, and can handle just about any looping tasks that you might be faced with. In fact, you can do a lot more with for loops that you probably ever thought possible. Beneath their deceptively simple syntax belies a highly malleable and extendable construct. The JavaScript interpreter is lenient both towards missing arguments the inclusion of extra ones. The latter is made possible by the oft overlooked comma operator. In today’s article, we’ll learn how to use the comma to extend each of the for loop statement’s three evaluation parts – initialize, condition, and increment – to take your for loops to a whole new level.

Basic Syntax

The for loop statement consists of four distinct parts:

for (initialize statement; condition statement; increment statement) {
    code block statements
}

Statements are run in the following order:

  • The Initialize Statement is executed before the loop starts.
  • The Condition Statement defines the condition for running the loop and executes before every loop iteration.
  • The Code Block executes every time that the condition statement evaluates to true.
  • The Increment Statement is executed each time after the loop (the code block) has been executed.

Here’s a simple example that prints the numbers 1 through 5:

var text = '';
for (i = 0; i < 5; i++) {
    text += i + "<br/>";
}
console.log(text);
/*
Outputs:
1
2
3
4
5
*/

Initializing Multiple Variables

Many people will declare variables both inside and outside of the loop body. Those declared outside the loop body will have a scope that extends past the end of loop execution, while those declared inside the loop block will be recreated on every iteration. Much of the time, neither of these options is ideal. Instead, consider declaring them in the for loop’s initialization block, separated by commas. Here’s some code that prints an array of cars to a DIV named “output”. In addition to the i incrementor, the len and text variables are also defined for later use:

var output = document.getElementById('output'),

    cars = [

      "Saab",

      "Volvo",

      "BMW",

      "Infiniti",

      "Honda",

      "Kia"

    ];

 

for (var i=0, len=cars.length, text="You've got "+len+" cars: 
"; i<len; i++) { text += cars[i] + "
"; } output.innerHTML += text;

Adding Conditions

Most people only use for loops to iterate over an array’s entire length from start to finish, but as we’ll see in this section, that doesn’t have to be the case. Rather than use a break statement to exit the loop early, you can append the exit test to the condition statement using a logical operator such as && or ||. Using our cars list above as an example, say that you wanted to exit the loop once you found a certain car, such as “BMW”. Here’s how to do that without an extra if statement in the loop body:

//shuffle the cars list
cars = cars.sort(function() {return Math.random() - 0.5});
for (var i=0; i<cars.length && cars[i] != 'BMW'; i++) {
  output.innerHTML += 'car #' + (i+1) + ' is a ' + cars[i] + '<br/>';
}

/*
Sample Output:
car #1 is a Saab
car #2 is a Volvo
*/

Using Multiple Incrementors

As this next example illustrates, not only can you initialize multiple variables to use in your for loop, but you can increment (and/or decrement) each of them in the increment statement as well. This function that I came across by Angus Croll simultaneously increments and decrements two counters within a for loop. The product of the counters is used to render an ascii curve. Another interesting trait of this loop is that he uses the counters’ product to exit. Rather than say b == 0 he uses the expression a*b. It’s easy to forget that the declared variables need not be explicitly tested against a particular value; as long as the expression evaluates to falsy at some point, the loop will terminate:

function renderCurve() {
  for(var a = 1, b = 10; a*b; a++, b--)
    output.innerHTML += new Array(a*b).join('*') + '<br/>';
}
 
renderCurve();

/*

Outputs:
*********
*****************
***********************
***************************
*****************************
*****************************
***************************
***********************
*****************
*********

*/

Conclusion

Using the comma to extend each of the for loop statement’s three evaluation parts – initialize, condition, and increment – you can entrust the for loop to handle a myriad of looping tasks that you might be faced with. In cases that it doesn’t work out, there’s always the while, do while, and for in loops to fall back on.

Rob Gravelle
Rob Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured