Loading...
Loading...

Control Flow in JavaScript

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.

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.

0 Interaction
2K Views
Views
28 Likes
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

Note: We aim to make learning easier by sharing top-quality tutorials.

We kindly ask that you refrain from posting interactions unrelated to web development, such as political, sports, or other non-web-related content. Please be respectful and interact with other members in a friendly manner. By participating in discussions and providing valuable answers, you can earn points and level up your profile.

$ Allow cookies on this site ? (y/n)

top-home