Control flow statements are used in JavaScript to control the order of execution of statements in a program based on certain conditions. The three main types of control flow statements in JavaScript are if/else statements, switch/case statements, and loops.
- If/else statements:
If/else statements are used to execute different blocks of code based on whether a certain condition is true or false.
Syntax:
if (condition) {
// code to execute if condition is true
} else {
// code to execute if condition is false
}
Example program:
let x = 5;
if (x > 2) {
console.log("x is greater than 2");
} else {
console.log("x is less than or equal to 2");
}
Output: “x is greater than 2”
- Switch/case statements:
Switch/case statements are used to select one of many blocks of code to execute based on the value of a given expression.
Syntax:
switch (expression) {
case value1:
// code to execute if expression equals value1
break;
case value2:
// code to execute if expression equals value2
break;
default:
// code to execute if expression doesn't match any of the cases
}
Example program:
let day = "Monday";
switch (day) {
case "Monday":
console.log("Today is Monday");
break;
case "Tuesday":
console.log("Today is Tuesday");
break;
default:
console.log("Today is neither Monday nor Tuesday");
}
Output: “Today is Monday”
- Loops:
Loops are used to repeat a block of code multiple times.
a. For loop:
For loop is used when you know how many times you need to execute a block of code.
Syntax:
for (initialization; condition; increment/decrement) {
// code to execute in each iteration
}
Example program:
for (let i = 1; i <= 5; i++) {
console.log(i);
}
Output:
1 2 3 4 5
b. While loop:
While loop is used when you don’t know how many times you need to execute a block of code, but you know the condition that must be met for the loop to continue.
Syntax:
while (condition) {
// code to execute in each iteration
}
Example program:
let i = 1;
while (i <= 5) {
console.log(i);
i++;
}
Output:
1 2 3 4 5
c. Do/while loop:
Do/while loop is similar to a while loop, but it executes the block of code at least once, even if the condition is false.
Syntax:
do {
// code to execute in each iteration
} while (condition);
Example program:
let i = 1;
do {
console.log(i);
i++;
} while (i <= 5);
Output:
1 2 3 4 5
Control flow statements are essential for controlling the order of execution of statements in a program. By understanding these statements, you can write more complex programs that make decisions and repeat actions based on certain conditions.