Control Flow
Control flow refers to the order in which statements are executed in a program. Programming languages provide various constructs to manage this order, allowing for conditional execution, repetition, and structured execution of code blocks.
Conditional Statements
Conditional statements allow you to execute different blocks of code based on whether a certain condition is true or false.
The if
Statement
The if
statement executes a block of code only if a specified condition is true.
Example: Simple if
if (temperature > 30) {
console.log("It's a hot day!");
}
The if...else
Statement
The if...else
statement executes one block of code if the condition is true, and another block if the condition is false.
Example: if...else
let score = 75;
if (score >= 60) {
console.log("You passed!");
} else {
console.log("You need to improve.");
}
The if...else if...else
Statement
This structure allows for multiple conditions to be checked in sequence.
Example: if...else if...else
let grade = 85;
if (grade >= 90) {
console.log("Grade: A");
} else if (grade >= 80) {
console.log("Grade: B");
} else if (grade >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: D or lower");
}
The switch
Statement
The switch
statement is a multi-way branching statement that compares a variable to a list of values and executes code based on the first match.
Example: switch
let day = "Monday";
switch (day) {
case "Monday":
console.log("Start of the week.");
break;
case "Friday":
console.log("End of the week!");
break;
default:
console.log("Just another day.");
}
The break
keyword is crucial within a switch
statement to prevent "fall-through" to the next case.
Logical Operators
Logical operators are used to combine or modify conditions within control flow statements.
&&
(Logical AND): True if both conditions are true.||
(Logical OR): True if at least one condition is true.!
(Logical NOT): Reverses the boolean value of a condition.
Example: Using Logical Operators
let isLoggedIn = true;
let isAdmin = false;
if (isLoggedIn && isAdmin) {
console.log("Welcome, Admin!");
} else if (isLoggedIn) {
console.log("Welcome, User!");
} else {
console.log("Please log in.");
}
Branching within Loops
Control flow statements also play a vital role in controlling loops.
break
: Exits the current loop entirely.continue
: Skips the rest of the current iteration and proceeds to the next.
Example: break
and continue
for (let i = 0; i < 10; i++) {
if (i === 3) {
continue; // Skips printing 3
}
if (i === 7) {
break; // Exits the loop when i reaches 7
}
console.log(i);
}
// Output: 0, 1, 2, 4, 5, 6