Control flow refers to the order in which individual statements, instructions, or function calls are executed in a program. In JavaScript, control flow can be managed through conditional statements and loops.
Control Flow in JavaScript
Conditional Statements
Conditional statements allow you to execute different code blocks based on certain conditions. The most common conditional statements are if
, else if
, and else
.
let age = 18;
if (age < 18) {
console.log("You are a minor.");
} else if (age >= 18 && age < 65) {
console.log("You are an adult.");
} else {
console.log("You are a senior.");
}
Switch Statement
The switch
statement is another way to perform control flow based on different conditions.
let fruit = "apple";
switch (fruit) {
case "banana":
console.log("You chose a banana.");
break;
case "apple":
console.log("You chose an apple.");
break;
default:
console.log("Unknown fruit.");
}
Loops
Loops allow you to execute a block of code multiple times. The most common types of loops in JavaScript are for
, while
, and do...while
.
For Loop
for (let i = 0; i < 5; i++) {
console.log(i);
}
While Loop
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
Do...While Loop
let j = 0;
do {
console.log(j);
j++;
} while (j < 5);
Breaking and Continuing Loops
You can control the flow of loops using the break
and continue
statements.
Break Statement
for (let i = 0; i < 10; i++) {
if (i === 5) {
break; // Exit the loop when i equals 5
}
console.log(i);
}
Continue Statement
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) {
continue; // Skip the even numbers
}
console.log(i); // Logs only odd numbers
}
Conclusion
Understanding control flow is crucial for writing efficient and effective JavaScript code. By using conditional statements and loops, you can control the execution of your code based on various conditions and repeat tasks as needed.
Note: We aim to make learning easier by sharing top-quality tutorials, but please remember that tutorials may not be 100% accurate, as occasional mistakes can happen. Once you've mastered the language, we highly recommend consulting the official documentation to stay updated with the latest changes. If you spot any errors, please feel free to report them to help us improve.