1. Introduction to Conditional Statements

Conditional execution, or control flow statements, are fundamental to programming in any language, including JavaScript. They enable a program to react and change its behavior based on different conditions, making it responsive and capable of handling various scenarios. Without conditional statements, code would always execute in the same way, which is often not what we need.

Imagine a program as a tree starting from a trunk and splitting into branches. The trunk represents the beginning of the program, and each conditional instruction represents a new branch. These instructions are executed based on user decisions, previous calculations, or other relevant data. JavaScript provides several ways to branch code execution based on conditions, and understanding these is crucial for effective programming.

2. The if Statement

The if statement is the most basic control flow instruction in JavaScript. It checks a condition and executes a block of code if the condition is true. The syntax is straightforward:

if (condition) {
    // block of code
}

Here, the if keyword is followed by a condition in parentheses. If the condition evaluates to true, the block of code within the curly brackets {} is executed. If the condition evaluates to false, the code block is skipped.

Example:

let isUserReady = confirm("Are you ready?");
if (isUserReady) {
    alert("User ready!");
}

In this example, an alert with the message "User ready!" is displayed only if the user clicks "OK" in the confirmation dialog.

Best Practices:

Always use curly brackets {} for the code block, even if it contains a single statement. This improves readability and reduces errors when adding more statements later.

Common Pitfall:

Consider this code:

let isUserReady = confirm("Are you ready?");
if (isUserReady)
    console.log("User ready!");
    alert("User ready!");

Here, the alert statement will execute regardless of the if condition because it’s not enclosed in the curly brackets of the if statement. Correcting it:

let isUserReady = confirm("Are you ready?");
if (isUserReady) {
    console.log("User ready!");
    alert("User ready!");
}

3. Scope and Blocks

Variables declared with let and const inside an if block are scoped to that block. They are not accessible outside it.

Example:

let unitPrice = 10;
let pieces = prompt("How many pieces do you order?", 0);
if (pieces > 0) {
    let total = unitPrice * pieces;
    console.log(total);
}
console.log(total); // Uncaught ReferenceError: total is not defined

In this example, total is defined only within the if block.

4. The if ... else Statement

Sometimes, you want to execute a different block of code if the condition is false. This is where the else keyword comes in.

Syntax:

if (condition) {
    // true block
} else {
    // false block
}

Example:

let isUserReady = confirm("Are you ready?");
if (isUserReady) {
    console.log("User ready!");
} else {
    console.log("User not ready!");
}

In this example, only one of the two messages will be logged, depending on the user's response.

5. The if ... else ... if Statement

For more complex decision making, you can chain multiple if ... else statements to handle multiple conditions.

if (condition1) {
    // code for condition1
} else if (condition2) {
    // code for condition2
} else {
    // code if none of the conditions are true
}

Example:

let number = prompt("Enter a number", 0);
if (number < 10) {
    alert("<10");
} else if (number < 30) {
    alert("<30");
} else if (number < 60) {
    alert("<60");
} else if (number < 90) {
    alert("<90");
} else if (number < 100) {
    alert("<100");
} else if (number == 100) {
    alert("100");
} else {
    alert(">100");
}

JavaScript will stop checking conditions after the first one that evaluates to true.

6. Conditional (Ternary) Operator

The ternary operator is a shorthand for if ... else statements. It allows you to assign a value to a variable based on a condition.

Syntax:

condition ? value_if_true : value_if_false;

Example:

let price = 100;
let shippingCost = price > 50 ? 0 : 5;
console.log(`price = ${price}, shipping = ${shippingCost}`); // -> price = 100, shipping = 0

7. The switch ... case Statement

The switch statement is used for multiple possible conditions. It evaluates an expression and matches its value against multiple case values.

Syntax:

switch (expression) {
    case value1:
        // code for value1
        break;
    case value2:
        // code for value2
        break;
    default:
        // code if no match
}

Example:

let gate = prompt("Choose gate: a, b, or c");
let win = false;
switch (gate) {
    case "a":
        alert("Gate A: empty");
        break;
    case "b":
        alert("Gate B: main prize");
        win = true;
        break;
    case "c":
        alert("Gate C: empty");
        break;
    default:
        alert("No gate " + String(gate));
}
if (win) {
    alert("Winner!");
}

The switch statement is often more readable than multiple if ... else if statements when dealing with many conditions.

8. Conclusion

Understanding and effectively using if, if ... else, if ... else if, the ternary operator, and switch statements are essential skills for any JavaScript programmer. These control flow statements allow you to write dynamic and responsive code, capable of handling a wide range of scenarios and conditions. Always strive to write clear, readable, and maintainable code by following best practices and using the appropriate control flow structures for each situation.

End Of Article

End Of Article