Skip to main content

Control Statements

Updated 2 min readMarkdown
Part of seriesDecode Javascript

Control statements are used to control the flow of execution of a program based on certain conditions.

  • Decision-making — Programs can choose different actions based on input or situations (e.g., if a user is logged in, show the dashboard).
  • Control program flow — They determine which block of code should execute.
  • Handle different situations — They allow programs to respond differently depending on the conditions.

Conditional Statements

Very often, when writing code, you want to perform different actions based on different decisions. You can use conditional statements to achieve this.

1️⃣ If statement

The if statement executes a block of code only if a specified condition is true.

// Syntax
if (condition) {
    // Code to be executed if condition is true
}

// Example
if (time < 10) {
    document.write("<b>Good morning</b>");
}

2️⃣ If...else statement

The if...else statement executes one block of code if the condition is true and another block if the condition is false.

// Syntax
if (condition) {
    // Code to be executed if condition is true
} else {
    // Code to be executed if condition is false
}

// Example
if (time < 10) {
    document.write("Good morning!");
} else {
    document.write("Good day!");
}

3️⃣ Switch statement

The switch statement is used to select and execute one block of code from multiple possible options based on an expression.

// Syntax
switch (expression) {
    case label1:
        // Execute code block 1
        break;

    case label2:
        // Execute code block 2
        break;

    default:
        // Code to execute if no case matches
}

Example:

switch (theDay) {
    case 5:
        document.write("Finally Friday");
        break;

    case 6:
        document.write("Super Saturday");
        break;

    case 0:
        document.write("Sleepy Sunday");
        break;

    default:
        document.write("I'm looking forward to this weekend!");
}

Note

  • case specifies a possible value to match.
  • break terminates the switch statement and prevents execution from continuing into the next case.
  • default executes when none of the cases match.

No comments yet. Be the first to comment.

Decode Javascript

Part 8 of 9

Explore JavaScript one concept at a time, from the fundamentals to advanced topics. Learn through clear explanations, practical examples, and code as we uncover how JavaScript works and use it to build for the web.

Up nextLooping StatementsLooping statements are used to execute the same block of code repeatedly as long as a specified condition is satisfied. Repetition — Allow the same block of code to execute multiple times without rew