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 errorconst arr = [1, 2, 3]let sum = 0;for (let i = 0; i <= arr.length; i++) {sum += arr[i]}const average = sum / arr.lengthconsole.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 = 64! = 4 * 3 * 2 * 1 = 24
Tests
- 1
You should define a function named
factorial. - 2
factorial(1)should return1. - 3
factorial(2)should return2. - 4
factorial(3)should return6. - 5
factorial(4)should return24. - 6
factorial(10)should return3628800.