JavaScript Control Flow Loops

For loop

A for loop executes the same code block until the specified condition becomes falsy. If the condition never becomes falsy, the loop will continue iterating forever, or until we manually break it.

The syntax for a for loop is written below.

for (initialExpression; conditionExpression; incrementExpression) {
// loop body
}

The three parts within the parentheses are individually optional. A for loop with nothing in the parantheses is called an infinite loop and loops forever.

The first part is where we initiate variables and is usually used to create and initialize a counter for the loop.

The second part is where we specify the condition of the loop. When the condition becomes falsy, the loop stops iterating.

The third part is where we specify what happens at the end of each iteration, and this is where we usually increment the counter variable we created in the first part.

Code example: count down from 5

for (let x = 5; x >= 0; x--) {
console.log(x)
}
// 5
// 4
// 3
// 2
// 1
// 0

Beginner mistake: off by one

The subtitle says beginner mistake, but off by one errors is probably the most common for-loop error regardless of experience.

Off by one errors happen when we let the loop run one iteration more or less than we intended to.

// intentional off by one error
const arr = [1, 2, 3]
let sum = 0;
for (let i = 0; i <= arr.length; i++) {
sum += arr[i]
}
const average = sum / arr.length
console.log(average) // NaN

We ran the loop one iteration too much, and ended up adding undefined to the sum variable which of course results in NaN.

Test yourself

Description

Define a new function with the name

factorial

that takes an integer input parameter and returns its factorial. The factorial of a positive integer n is the product of all positive integers less than or equal to n, and is denoted by n!.

3! = 3 * 2 * 1 = 6
4! = 4 * 3 * 2 * 1 = 24

Tests

  1. 1 You should define a function named factorial.
  2. 2factorial(1) should return 1.
  3. 3factorial(2) should return 2.
  4. 4factorial(3) should return 6.
  5. 5factorial(4) should return 24.
  6. 6factorial(10) should return 3628800.
Editor