Loops
You'll learn to repeat code with for, for...of and while, and to count how many times a loop runs.
Watch & read
Start with the required ones. The others are there when you need them.
See it step by step
Watch a for loop count, check and add, round by round.
Explanation
You want to do the same thing many times: add up 30 students' marks, or print every player in a team. Copying the same line 30 times is slow and easy to get wrong. A loop repeats a block of code for you.
The classic loop is for. It has three parts inside the brackets, split by ;:
for (let i = 1; i <= 3; i++) {console.log(i);}// 1, then 2, then 3
Read it like a cricket over counter. Start at i = 1. Keep going while i <= 3 is true. After
each round, do i++, which adds 1 to i. Each round is called an iteration.
Often you have a list of values in square brackets, called an array: [70, 85, 60]. You'll meet
arrays properly soon. To visit each item, for...of is the easiest loop:
for (const mark of [70, 85, 60]) {console.log(mark);}
while is the simplest loop: while (balance > 0) { ... } repeats as long as the condition is true.
Make sure something inside changes, or it never stops.
People often make an off-by-one mistake: the loop runs one time too many or too few. i < 5 stops
before 5; i <= 5 includes 5. When you count from 0, use <. When you count from 1, use <=.
Later you'll see map and filter. They are loops with a job already built in: make a new list, or keep
some items. In React you'll use them more than for, but they work the same way underneath.
When you read a loop, find three things: where it starts, when it stops, and what changes each round.
Code tour
Click a line number with a ring to read the note for that line.
Practice
Short drills. Take your time and read the code before you answer.
1for (let i = 0; i < 3; i++) {2 console.log(i);3}
sum ends at 15 and the loop runs 5 times. Fix the code so both checks pass.Quick check
3 questions. Each one explains itself after you answer.
- 1 / 3How many times does
for (let i = 0; i < 5; i++)run? - 2 / 3In
for (const name of ["Tamim", "Liton"]), what isnamein the second round? - 3 / 3
let n = 3; while (n > 0) { n = n - 1; }What isnafter the loop?
Explain it back
How confident are you with Loops?
Done
for loop and say how many times it runs and what each variable holds at the end.