Javascript Loops and Iterations
Loops
In JavaScript, loops are used to repeatedly execute a block of code until a certain condition is met.
for loop
Consists of 3 parts: initialisation (initial state), condition (to fulfill), and update (change between iterations):
for (initialization; condition; increment/decrement) {
// code block to be executed
}
// example
for (let i = 0; i < 5; i++) {
console.log(i);
}
while loop
A block of code is repeatedly executed until a condition is met:
while (condition) {
// code to be executed
}
// example
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
do...while loop
Similar with the one above but condition is before each time the block of code is executed - NB: this means that the block will never be executed if the initial condition is not met:
do {
// code to be executed
} while (condition);
// example
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
Iterations
There are couple of way to iterate over the elements of an "iterable" object - eg: arrays, objects, sets.
for...in loop
Iterates over the properties of an object:
const person = {
name: 'Charlie',
city: 'London'
};
for (const prop in person) {
console.log(`${prop}: ${person[prop]}`);
}
// prints:
// name: Charlie
// city: London
for...of loop
Provides a concise loop to iterate over an array:
const people = ['Charlie', 'Paul'];
for (const person of people) {
console.log(person);
}
// prints:
// Charlie
// Paul
forEach loop
Provides a way to iterate over an array via an anonymous function:
const people = ['Charlie', 'Paul'];
people.forEach((person) => {
console.log(person);
});
// prints:
// Charlie
// Paul
Break & Continue
break
and continue
provide a way to alter the flow of a loop or iteration in certain conditions:
break
terminates the loopcontinue
skip the rest of the current iterations and proceeds to the next
const numbers = [1, 2, 3, 4, 5];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] === 3) {
console.log('Found 3!');
break; // terminate the loop
}
if (numbers[i] % 2 === 0) {
continue; // skip even numbers
}
console.log(numbers[i]);
}
// prints
// 1
// Found 3!
In the example above, the loop will finish when the value at the iteration index is "3" and will only print odd numbers to the console. Notice that "3" doesn't get printed to the console since the break
is invoked earlier in that iteration.