Understanding and using control flow structures in JavaScript
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.
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");
}
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");
}
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);
}
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++;
}
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);
}