Loops: for, while and for...of
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
Why loops
If you want to print the numbers from 1 to 100, you do not write 100 lines. You write a loop. A loop repeats a block of code as long as a condition holds or for every item in a collection.
The for loop
The classic loop has three parts in the brackets: a start, a condition and a step.
for (let i = 1; i <= 5; i++) {
console.log("Round " + i);
}
It prints Round 1 to Round 5. Here is the order of events:
let i = 1runs once, at the start.i <= 5is checked. If it is true, the body runs.- After the body,
i++adds one. - Go back to step 2. When the condition becomes false, the loop ends.
A loop that counts to a total is a good first example. Here we add up 1 to 100:
let sum = 0;
for (let n = 1; n <= 100; n++) {
sum += n;
}
console.log(sum); // 5050
Counting from zero is the norm in programming, because array positions start at zero:
const fruits = ["mango", "apple", "banana"];
for (let i = 0; i < fruits.length; i++) {
console.log(i, fruits[i]);
}
Notice i < fruits.length and not <=. With three items the valid positions are 0, 1 and 2. Using <= would try to read position 3, which does not exist, and you would get undefined. This off-by-one error is very common.
for...of
When you just want each item and not its position, for...of is simpler:
const fruits = ["mango", "apple", "banana"];
for (const fruit of fruits) {
console.log(fruit.toUpperCase());
}
There is no counter to manage, and no chance of an off-by-one error. It also works on strings, giving you one character at a time:
for (const letter of "abc") {
console.log(letter);
}
I use for...of by default and a classic for only when I need the index or a special step, such as counting down or by twos.
while and do...while
Use while when you do not know in advance how many rounds you need.
let balance = 1000;
let years = 0;
while (balance < 2000) {
balance = balance * 1.1; // 10% growth
years++;
}
console.log(years); // 8
The condition is checked before every round. If it is false at the start, the body never runs.
A do...while loop checks the condition after the body, so it always runs at least once:
let attempts = 0;
do {
attempts++;
console.log("Attempt " + attempts);
} while (attempts < 3);
break and continue
break leaves the loop immediately. continue skips the rest of this round and jumps to the next.
const numbers = [4, 9, 12, 7, 20, 3];
for (const n of numbers) {
if (n % 2 !== 0) continue; // skip odd numbers
if (n > 15) break; // stop when we pass 15
console.log(n);
}
This prints 4 and 12. Then 20 is greater than 15, so the loop stops before reaching the 3.
Looping over an object
for...of is for arrays and strings. For the keys of an object use for...in, or better, Object.entries:
const scores = { ali: 80, sara: 92, omar: 75 };
for (const [name, score] of Object.entries(scores)) {
console.log(`${name}: ${score}`);
}
The square brackets in [name, score] unpack each pair into two variables. We will cover that syntax properly in the follow-up course. For now, just copy the pattern.
Nested loops
You can put a loop inside another loop. A multiplication table is the classic example:
for (let row = 1; row <= 3; row++) {
let line = "";
for (let col = 1; col <= 3; col++) {
line += row * col + "\t";
}
console.log(line);
}
The inner loop runs completely for every round of the outer loop. With 3 by 3, the body runs 9 times. With big numbers that grows fast, so be careful when looping inside loops over large data.
Common mistakes
- Infinite loops. If the condition never becomes false, the program hangs. Check that something inside the loop moves it toward the end, such as
i++. If your browser tab freezes, this is the likely reason. - Off-by-one errors. Use
< array.length, not<=. - Using var in a for loop. It leaks out of the loop and causes odd behaviour with callbacks. Use
let. - Changing an array while looping over it. Removing items while you iterate skips elements. Build a new array instead.
- Using for...in on arrays. It gives you string keys and may include extras. Use
for...of.
Try it yourself
- Print the numbers from 10 down to 1, then print "Go".
- Use a loop to add up only the even numbers from 1 to 50.
- Given
["Ali", "Sara", "Omar"], print a numbered list like1. Ali. - Write a
whileloop that doubles a number starting from 1 and stops when it is greater than 1000. Print how many doublings it took.
for (let i = 1; i <= 5; i++) {
console.log("Round " + i);
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account