JavaScript If Else

Conditional statements like if and else let you run code only if certain conditions are met. They form the basis of branching logic, controlling the flow of your program.

Key Topics

Basic if/else

The if statement executes code if a condition is true, otherwise else can handle the other scenario.

let x = 10;
if (x > 5) {
    console.log("Greater than 5");
} else {
    console.log("5 or less");
}

Output

> Greater than 5

Explanation: Since x is 10, the condition x > 5 is true, executing the first block.

else if

else if allows multiple conditions to be checked in sequence.

let y = 5;
if (y > 10) {
    console.log("Greater than 10");
} else if (y === 5) {
    console.log("Equals 5");
} else {
    console.log("Less than 5");
}

Output

> Equals 5

Explanation: The second condition matches exactly, so "Equals 5" is printed.

Nested if Statements

You can nest if statements inside others to check multiple layers of conditions.

let z = 20;
if (z > 10) {
    if (z < 30) {
        console.log("Between 10 and 30");
    } else {
        console.log("30 or more");
    }
} else {
    console.log("10 or less");
}

Output

> Between 10 and 30

Explanation: Since z is 20, the outer condition passes, and the inner condition checks for being less than 30, which also passes.

JavaScript Usage in DOM

Use if/else to alter webpage elements, styling, or content based on user actions or data conditions.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>if else in DOM</title>
</head>
<body>
    <h1>if/else Demo</h1>
    <input type="text" id="inputVal" placeholder="Enter a word">
    <button onclick="checkWord()">Check</button>
    <p id="message"></p>

    <script>
        function checkWord() {
            let word = document.getElementById("inputVal").value;
            if (word === "hello") {
                document.getElementById("message").textContent = "You said hello!";
            } else {
                document.getElementById("message").textContent = "You didn't say hello";
            }
        }
    </script>
</body>
</html>

Key Takeaways

  • if/else: Branches code execution based on conditions.
  • else if: Checks multiple conditions in order.
  • Nested if: Multiple layers of conditions for complex logic.
  • DOM Integration: Adjust UI or behavior based on conditional logic.