JavaScript Control Flow

Understanding and using control flow structures in JavaScript

JavaScript Control Flow

Control flow is the order in which individual statements, instructions or function calls are executed or evaluated in a program. JavaScript provides several structures to control the flow of your code.

If...Else Statements

The if...else statement executes a block of code if a specified condition is true. If the condition is false, another block of code can be executed.

let age = 18;
if (age >= 18) {
console.log("You are an adult");
} else {
console.log("You are a minor");
}

Switch Statements

The switch statement is used to perform different actions based on different conditions.

let day = "Monday";
switch (day) {
case "Monday":
console.log("It's Monday");
break;
case "Tuesday":
console.log("It's Tuesday");
break;
default:
console.log("It's another day");
}

For Loops

The for loop repeats a block of code as long as a certain condition is met.

for (let i = 0; i < 5; i++) {
console.log("Iteration: " + i);
}

While Loops

The while loop repeats a block of code while a specified condition is true.

let count = 0;
while (count < 5) {
console.log("Count: " + count);
count++;
}

Try...Catch Statements

The try...catch statement marks a block of statements to try and specifies a response should an exception be thrown.

try {
// Code that may throw an error
ㅤㅤconsole.log(nonExistentVariable);
} catch (error) {
console.log("An error occurred: " + error.message);
}