SHARE
Facebook X Pinterest WhatsApp

Getting Fancy with the JavaScript For Loop

Written By
thumbnail
Rob Gravelle
Rob Gravelle
Mar 13, 2015

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.

Recommended for you...

The Revolutionary ES6 Rest and Spread Operators
Rob Gravelle
Aug 23, 2022
Ahead of Time (AOT) Compilation in Angular
Tariq Siddiqui
Aug 16, 2022
Converting a JavaScript Object to a String
Rob Gravelle
Aug 14, 2022
Understanding Primitive Type Coercion in JavaScript
Rob Gravelle
Jul 28, 2022
HTML Goodies Logo

The original home of HTML tutorials. HTMLGoodies is a website dedicated to publishing tutorials that cover every aspect of being a web developer. We cover programming and web development tutorials on languages and technologies such as HTML, JavaScript, and CSS. In addition, our articles cover web frameworks like Angular and React.JS, as well as popular Content Management Systems (CMS) that include WordPress, Drupal, and Joomla. Website development platforms like Shopify, Squarespace, and Wix are also featured. Topics related to solid web design and Internet Marketing also find a home on HTMLGoodies, as we discuss UX/UI Design, Search Engine Optimization (SEO), and web dev best practices.

Property of TechnologyAdvice. © 2025 TechnologyAdvice. All Rights Reserved

Advertiser Disclosure: Some of the products that appear on this site are from companies from which TechnologyAdvice receives compensation. This compensation may impact how and where products appear on this site including, for example, the order in which they appear. TechnologyAdvice does not include all companies or all types of products available in the marketplace.