JavaScript Control Structures - CodingQue

JavaScript Control Structures

Control structures in JavaScript help direct the flow of code execution. This page covers conditional statements, switch cases, and loops, each with examples to understand their use cases.

1. Conditional Statements

Conditional statements in JavaScript execute code based on specific conditions. The most common ones are if and else statements.

Example: The following code checks if a person is an adult:

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

2. Switch Cases

The switch statement is an alternative to using multiple if...else statements. It checks a variable or expression against multiple possible values.

Example: The following code outputs a different message based on the day:

let day = "Monday";
switch (day) {
    case "Monday":
        console.log("Start of the week!");
        break;
    case "Friday":
        console.log("Almost the weekend!");
        break;
    default:
        console.log("It's just another day.");
}

3. Loops

Loops are useful when you need to repeat a block of code multiple times. Common types of loops in JavaScript include for, while, and do...while loops.

For Loop

The for loop repeats a block of code a specified number of times.

Example: The following code outputs numbers from 0 to 4:

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

While Loop

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

Example: The following code outputs numbers from 0 to 4 using a while loop:

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

Do...While Loop

The do...while loop is similar to the while loop, but it guarantees that the code block runs at least once, even if the condition is false.

Example: The following code outputs the value of i once, even though the condition is false:

let i = 5;
do {
    console.log(i);
    i++;
} while (i < 5);
Previous Next
Modern Footer