For Loops

Again, and again, and again, and...

Counting

Remember when we used a while loop to count?

let count = 1;
while (count <= 10) {
  console.log(`Count is ${count}`);
  count++;
}

The for loop allows us to do this in a more concise fashion.

for (let count = 1; count <= 10; count++) {
  console.log(`Count is ${count}`);
}

Initialize...

The bit before the first semicolon inside a for statement runs before looping begins:

for(let count = 1;)

You may hear this called many things. We will call it the initialization expression.

This is analogous to how we initialized count before our while loop:

let count = 1;

Loop While...

Our loop condition is the same and even in pretty much the same spot:

for(let count = 1; count < 10;)
int count = 1;

while(count < 10)

Afterwards...

A for loop that follows the standard pattern makes it easy for us to find what happens after the loop.

for(let count = 1; count <= 10; count++) {
  console.log(`Count is ${count}`);
}
int count = 1;
while(count <= 10) {
  console.log(`Count is ${count}`);
  count++;
}

I am NOT a Number!

Our initialization expression is usually a number, but initialize pretty much anything we like. Also, our increment expression is often used to decrement, but you can also get weird:

const input = require("readline-sync");

for (let r = "foo"; !(r === "quit"); r = input.question("What should I do? ")) {
  console.log(r);
}

console.log("Ok, I quit!");

Yeah, probably don't do that. It's not good-weird.

Note: we're using r as the variable name for brevity. The name should be more descriptive.


Leaving Out Bits

Each of these three parts is optional. This:

for (; myCondition; ) {
  // do something
}

is the same as:

while (myCondition) {
  // do something
}

Which of these is easier to read? As developers, we want to write code that minimizes the cognitive load required to understand it. Ideally, we also avoid disturbing fellow developers. Don't be cute. Just use a while statement.


Summary

When it's appropriate to use, a for loop is generally easier to read.

Including initialization and incrementing in a consistent spot also makes it less prone to error than a comparable while loop.