Javascript Control Flow

JavaScript if else Statement


In programming, making decisions based on certain conditions is essential. JavaScript provides several constructs to handle decision-making scenarios effectively. Let's explore these constructs:

1. if Statement:

The if statement allows you to execute a block of code if a specified condition is true.

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

2. if...else Statement:

The if...else statement allows you to execute one block of code if the condition is true and another block if the condition is false.

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

3. if...else if...else Statement:

The if...else if...else statement allows you to check multiple conditions and execute a block of code based on the first condition that is true.

if (condition1) {
    // Code to be executed if condition1 is true
} else if (condition2) {
    // Code to be executed if condition2 is true
} else {
    // Code to be executed if no condition is true
}

4. Nested if...else Statement:

You can nest if...else statements inside another if or else block to handle more complex decision-making scenarios.

if (condition1) {
    if (condition2) {
        // Code to be executed if both condition1 and condition2 are true
    } else {
        // Code to be executed if condition1 is true but condition2 is false
    }
} else {
    // Code to be executed if condition1 is false
}

Example Usage:

const number = prompt("Enter a number: ");

if (number > 0) {
    console.log("The number is positive");
} else if (number == 0) {
    console.log("The number is zero");
} else {
    console.log("The number is negative");
}

These decision-making constructs are fundamental in JavaScript programming and are used extensively to control the flow of execution based on various conditions. Understanding and mastering them is essential for writing efficient and logical code.