Wednesday, June 21, 2023

JavaScript if....Else

 

JavaScript if, else, and else if

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions.

You can use conditional statements in your code to do this.

In JavaScript we have the following conditional statements:

  • Use if to specify a block of code to be executed, if a specified condition is true
  • Use else to specify a block of code to be executed, if the same condition is false
  • Use else if to specify a new condition to test, if the first condition is false






  • Use switch to specify many alternative blocks of code to be executed    

    The if Statement

    Use the if statement to specify a block of JavaScript code to be executed if a condition is true.

    Example  

    <html>

    <body>


    <h2>JavaScript if</h2>


    <p>Display "Good day!" if the hour is less than 18:00:</p>


    <p id="demo">Good Evening!</p>


    <script>

    if (new Date().getHours() < 18) {

      document.getElementById("demo").innerHTML = "Good day!";

    }

    </script>


    </body>

    </html>

  • The else Statement

    Use the else statement to specify a block of code to be executed if the condition is false.

  • Example  

  • <!DOCTYPE html>
    <html>
    <body>

    <h2>JavaScript if .. else</h2>

    <p>A time-based greeting:</p>

    <p id="demo"></p>

    <script>
    const hour = new Date().getHours(); 
    let greeting;

    if (hour < 18) {
      greeting = "Good day";
    } else {
      greeting = "Good evening";
    }

    document.getElementById("demo").innerHTML = greeting;
    </script>

    </body>
    </html>




No comments:

Post a Comment

JavaScript Animated

  JavaScript Animated <!DOCTYPE html> <html> <style> #myContainer {   width: 400px;   height: 400px;   position: relative;...