If statement

Let's say John has 23 apples and Tom has 45 apples. We want to check who has more apples using JavaScript programming. We need to make our browser understand the if statement.

Note

The if statement compares two variables.

To check our condition, we need to declare the two variables containing the number of apples, as follows:

var john = 23;
var tom = 45;

To check which number is bigger, we can apply the if statement as shown in the following:

if(john > tom)
{
  alert("John has more apples than tom");
}

Let's say that we do not know which variable is bigger. Then, we need to check both the variables. Therefore, we need to include the following codes to our program:

if(tom > john )
{
  alert("Tom has more apples than John");
}

The whole code in an HTML page will be as follows:

<html>
  <head>
    <title>
      If statement
    </title>
  </head>
  <body>
    <script type="text/javascript">
      var john = 23;
      var tom = 45;
      if(john > tom){
        alert("John has more apples than Tom");
      }
    if(tom> john ){
      alert("Tom has more apples than John");
    }
    </script>
  </body>
</html>

The output will be as follows:

If statement

You learned about the conditional operators in the previous chapters. In if statement, you can use all of them. Here are a few examples with comments:

If(tom => john){
//This will check if the number of apples are equal or greater. 
}
If(tom <= john)
{
//This will check if the number of apples are equal or less. 
}
If(tom == john)
{
//This will check if the number of apples are equal. 
}

To check multiple conditions, you need to use OR (||) or AND (&&).

Consider the following examples:

If(john == 23 || john => tom)
{
/* This will check if John has 23 apples or the number of John's apple is equal to or greater than Tom's. This condition will be full filled if any of these two conditions are true. 
*/
}
If(tom == 23 && john <= tom)
{
/* This will check if Tom has 23 apples or the number of john's apple is less than Tom's or equal. This condition will be full filled if both of these two conditions are true. 
*/
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.194.39