What are Control Flow Statements?
Control Flow Statements are used to control the order in which code executes in a program.
Using control flow statements, we can decide:
- Which code should run.
- Which code should be skipped.
- How many times a block of code should run.
JavaScript provides different types of control flow statements.
Some common control flow statements are:
- if
- if...else
- else if
- switch
- for loop
- while loop
1. if Statement
The if statement executes a block of code only when the condition is true.
let marks = 80;
if (marks >= 50) {
console.log("Pass");
}
Explanation
-
let marks = 80;→ A variable namedmarksis created with the value80. -
if (marks >= 50)→ Checks whether the marks are greater than or equal to 50. - Since the condition is true,
"Pass"is printed.
2. if...else Statement
The if...else statement executes one block if the condition is true and another block if the condition is false.
let age = 15;
if (age >= 18) {
console.log("Eligible to Vote");
} else {
console.log("Not Eligible to Vote");
}
Explanation
-
agestores the value15. - The condition checks whether age is greater than or equal to
18. - The condition is false, so the
elseblock executes. -
"Not Eligible to Vote"is printed.
3. else if Statement
The else if statement is used to check multiple conditions.
let score = 70;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 60) {
console.log("Grade B");
} else {
console.log("Grade C");
}
Explanation
-
scorestores the value70. - The first condition (
score >= 90) is false. - The second condition (
score >= 60) is true. - So,
"Grade B"is printed.
4. switch Statement
The switch statement is used when we have multiple choices.
let day = 6;
switch (day) {
case 1:
console.log("Monday");
break;
case 6:
console.log("Saturday");
break;
default:
console.log("Invalid Day");
}
Explanation
-
daystores the value6. - The switch checks all cases.
-
case 6matches the value. -
"Saturday"is printed. -
breakstops further execution.
5. for Loop
The for loop is used when we know how many times the code should run.
for (let i = 1; i <= 3; i++) {
console.log("Hello");
}
Explanation
-
let i = 1→ Loop starts from1. -
i <= 3→ Loop runs whileiis less than or equal to3. -
i++→ Increases the value ofiby1. -
"Hello"is printed three times.
6. while Loop
The while loop executes as long as the condition is true.
let i = 1;
while (i <= 3) {
console.log(i);
i++;
}
Explanation
-
istarts with the value1. - The loop checks whether
iis less than or equal to3. - The value of
iis printed. -
i++increases the value by1. - The loop stops when
ibecomes4.
Today, I learned about JavaScript Control Flow Statements such as if, if...else, else if, switch, for, and while. These statements help us control the execution of code and make decisions based on different conditions.
Thank you for reading my blog. I will meet you in the next blog with another JavaScript topic. 👋
Top comments (0)