Control flow refers to the sequence in which statements are executed within a program. By default, control flow follows a linear path where statements are processed in the order they appear in the program file, reading from left to right and from top to bottom.
The control flow executes from the first line and till the last line, unless and until computer execution goes through conditionals and loops.
These statements allow you to execute different blocks of code based on given conditions.
// Conditional Statements
if (condition) {
// if condition is true
} else {
// if condition is false
}
// Switch Statement
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
// code to be executed if expression doesn't match any case
}
It provides a way to execute different code blocks based on different cases.
// Loops
for (initialization; condition; increment/decrement) {
// code to be executed
}
while (condition) {
// code to be executed
}
do {
// code to be executed
} while (condition);
These structures allow you to execute a block of code repeatedly.
// Loops
for (initialization; condition; increment/decrement) {
// code to be executed
}
while (condition) {
// code to be executed
}
do {
// code to be executed
} while (condition);
These keywords allow you to alter the flow within loops. Break terminates the loop, while continue skips the current iteration and moves to the next.
// Break and Continue
for (let i = 0; i < 5; i++) {
if (i === 3) {
break; // terminates the loop when i equals 3
}
console.log(i); // will print 0, 1, 2
}
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // skips the iteration when i equals 2
}
console.log(i); // will print 0, 1, 3, 4
}