Jasyn Marais

Control Structures

17 February 2023

Control structures are used to control the flow of execution in a program. There are several control structures in JavaScript, including:

Conditional statements

These are used to execute code based on a condition. The two most common conditional statements in JavaScript are if and switch.

if statement

This statement allows you to execute code if a certain condition is met. Here is an example:

let a = 5;

if (a > 0) {
    console.log("a is positive");
}

In this example, the if statement checks whether a is greater than 0. If the condition is true, the message "a is positive" is logged to the console.

switch statement

This statement allows you to execute different code based on the value of an expression. Here is an example:

let fruit = "apple";

switch (fruit) {
    case "banana":
        console.log("I love bananas");
        break;
    case "apple":
        console.log("I like apples");
        break;
    default:
        console.log("I don't like this fruit");
}

In this example, the switch statement checks the value of the fruit variable and executes a different block of code depending on the value. Since the value of fruit is "apple", the message "I like apples" is logged to the console.

Loops

These are used to repeat code a certain number of times or until a certain condition is met. The three most common types of loops in JavaScript are for, while, and do-while.

for loop

This loop allows you to execute code a certain number of times. Here is an example:

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

In this example, the for loop executes the code inside the curly braces 5 times. The i variable starts at 0 and is incremented by 1 each time through the loop.

while loop

This loop allows you to execute code until a certain condition is no longer true. Here is an example:

let i = 0;

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

In this example, the while loop executes the code inside the curly braces as long as the condition i < 5 is true. The i variable starts at 0 and is incremented by 1 each time through the loop.

do-while loop

This loop is similar to the while loop, but the code inside the loop is executed at least once, even if the condition is false. Here is an example:

let i = 0;

do {
    console.log(i);
    i++;
} while (i < 5);

In this example, the do-while loop executes the code inside the curly braces at least once, and then continues to execute the code as long as the condition i < 5 is true. The i variable starts at 0 and is incremented by 1 each time through the loop.

These are just a few examples of the control structures available in JavaScript. They allow you to create more complex programs by controlling the flow of execution based on certain conditions or values.