Tag Archives: conditional

Making comparisons in C# (if, else if, and else statements)

In this tutorial you will learn how to make comparisons in C# using the following conditional statements:

  • if
  • else if
  • else

We can check, for example, if a number is less than, greater than, less than or equal to, greater than or equal to, equal to, or not equal to another number. We can also check if a string variable is equal to another string value (for example, checking if a password is correct). To make comparisons, we will need to be familiar with comparison operators.

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Watch the video below which shows how to make comparisons using if, else if, and else statements (scroll down for the sample code).

Sample code

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      int x = 11;

      if (x > 10)
      {
        Console.WriteLine("x is greater than 10");
      }
      else if (x < 10)
      {
        Console.WriteLine("x is less than 10");
      }
      else{
        Console.WriteLine("x is equal to 10");
      }
    }
  }
}

Logical operators

We can also check if multiple conditions evaluate to true or if at least one of multiple conditions evaluate to true in a single if statement using logical operators. Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s first name is “Joe” AND their last name is also “Bloggs”.

if (firstName == "Joe" && lastName == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Watch the video below to see how you can use logical operators in conditional statements and then scroll down for the sample code.

Sample code using logical OR operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Smith";

      if (firstName == "Joe" || lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Sample code using logical AND operator

using System;

namespace MyCSharpProject
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      string firstName = "Joe";
      string lastName = "Bloggs";

      if (firstName == "Joe" && lastName == "Bloggs")
      {
        Console.WriteLine("Hi Joe.");
      }
      else{
        Console.WriteLine("I don't know you.");
      }
    }
  }
}

Next tutorial: Switch statements in C#

Switch statements in C#

We have looked at how to use if statements for conditional programming in C#. However, there is something else we can use if there are many different conditions or cases we want to test. We can use switch statements. Switch statements can contain a number of ‘cases’ and a ‘default’ if none of the specified cases are chosen or met.

Have a look at the sample code below. In this program, the user is asked to enter a number between 1 and 5. Based on the number the user enters, they will be presented with an interesting fact about that number. Each number is a different case and there is also ‘default’ case that will be used if the user does not enter one of those 5 numbers.

Each case also uses a ‘break’ so that if a case is met, then the other cases will not also be checked. In other words, the switch statement will end as soon as a case is met. Here is the sample code:

using System;

namespace MyCSharpApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      // Ask the user to enter a number between 1 and 5
      Console.WriteLine ("Enter a number between 1 and 5 for an interesting fact:");
      int number = int.Parse( Console.ReadLine ());

      switch (number) {
      case 1:
        Console.WriteLine ("1 is the number of websites that existed in 1991.");
        break;
      case 2:
        Console.WriteLine ("2 is the only even prime number.");
        break;
      case 3:
        Console.WriteLine ("3 is the number of days you can survive without water (on average).");
        break;
      case 4:
        Console.WriteLine ("4 is the number of miles per second that space junk moves around Earth.");
        break;
      case 5:
        Console.WriteLine ("5 is the length in meters of a Great White Shark.");
        break;
      default:
        Console.WriteLine ("You did not select a valid option.");
        break;
      }

      Console.ReadLine ();
    }
  }
}

Here is an example of what the user will see when they enter the number 4…

switch_cs_example

Note: When copying the code, only copy the actual code you need. The code above uses a namespace that may be different to the name of your project or solution. If you copy all of the code above and replace all of your code with it, then make sure you change the namespace name above to match the one in your project.

Conditional programming in C#

Conditional statements are used so that your program can make decisions based on different conditions. For example, a game might display a message to the player if their score is higher than a certain number. Or an app might provide different content based on its user’s age. When your program has a range of conditions, you can build powerful algorithms.

Watch the video below and then scroll down to view the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
   Console.WriteLine("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if statements allow you to specify what action will occur when a condition is met and else statements can be used to run another piece of code if the condition is not met. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else
{
   Console.WriteLine("You are not old enough to vote");
}

else if statement

The limitation of using just if and else statements is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the else if statement comes in.

Using else if statements allows you to test multiple conditions. You can have several else if statements that each test a different condition. The else part is optional when using if and else if statements but is handy if you want something to happen if none of the specified conditions are met.

Here is some sample code for the ifelse if and else statements:

if(age>=18)
{
   Console.WriteLine("You are old enough to vote");
}
else if(age==17)
{
   Console.WriteLine("You can vote after your next birthday");
}
else
{
   Console.Writeline("You are not old enough to vote");
}

Sample C# code

Here is the sample C# code used in the video. Comments have been added to the code to explain each part of the code.

using System;

namespace MyCSharpApp
{
  class MainClass

  {
    public static void Main (string[] args)
    {
      // Ask the user to select an option (type of calculation)
      // \n will create a new line
      Console.WriteLine ("Select from one of the following options: \n1 - Add\n2 - Subtract\n3 - Multiply\n4 - Divide");

      // Store the selected option in a variable as an integer value (1, 2, 3, or 4)
      int option = int.Parse (Console.ReadLine ());

      // Ask the user to enter two numbers
      Console.WriteLine ("Enter two numbers...");

      // Store the first number in a variable as a float value
      float num1 = float.Parse(Console.ReadLine ());

      // Ask the user to enter the first of the two numbers
      Console.WriteLine ("Enter the first number:");

      // Ask the user to enter the second of the two numbers
      Console.WriteLine ("Enter the second number:");

      // Store the second number in a variable as a float value
      float num2 = float.Parse(Console.ReadLine ());

      // check the option selected and display the result of the relevant calculation

      // if option 1 (add) was selected...
      if (option == 1) {
        Console.WriteLine ("The answer is: " + (num1 + num2));
      }

      // if option 2 (subtract) was selected...
      else if (option == 2) {
        Console.WriteLine ("The answer is: " + (num1 - num2));
      }

      // if option 3 (multiply) was selected...
      else if (option == 3) {
        Console.WriteLine ("The answer is: " + (num1 * num2));
      }

      // if option 4 (divide) was selected...
      else if (option == 4) {
        Console.WriteLine ("The answer is: " + (num1 / num2));
      } 

      // if no option was selected...
      else {
        Console.WriteLine ("Option is not recognised");
      }
    }
  }
}

Comparison operators

Comparison (or equality) operators are used to compare two values. The result of using an equality operator can either be true or false. The only type of variable that can store the result of an equality operator is a Boolean. The table below describes the comparison operators used in C#.

Operator Description
== This operator is used to check if two values are equal eg. x == 5 would return true if x had a value of 5.
> and < The ‘greater than’ and ‘less than’ operators are used to check if values are greater than or less than another value. For example, x > 5 (if the value of x was 3 than it would return false).
>= and <= The ‘greater than or equal to’ and ‘less than or equal to’ operators are similar to the ‘greater than’ and ‘less than’ operators. For examples, 5>=5 would return true because 5 is equal to 5, and 6<=10 would return true because 6 is less than 10.
!= The ‘not equal’ operator is used to check if two values are not the same as each other. For example, x != 10 would return true if the value of x was 9 because 9 is not equal to 10. However, y != 5 would return false if the value of y was 5.

Logical operators

Logical operators are used for complex conditions. The table below describes each logical operator.

Operator Description
&& This is known as the AND operator and is used to check if both values are true in a complex condition.
|| The is known as the OR operator and is used to check if at least one of the values is true when two values are compared. It will return true if either one or both values are true.
! This is known as the NOT operator and will return the opposite of a Boolean value. For example !true; would return false and !false; would return true.

Here is an example of using the && logical operator to display a message only if a user’s firstname is “Joe” AND their last name is also “Bloggs”.

if (first_name == "Joe" && last_name == "Bloggs")
{
   Console.WriteLine("Hello Joe Bloggs.");
}
else
{
   Console.WriteLine("I don't know you.");
}

Next tutorial: While loops in C#

Do while loops in PHP

In the previous tutorial, we looked at how while loops can be used to test a condition before running a loop. While that test condition evaluates to true, the loop will continue running. The while loop tests a condition before the loop runs and will not run the loop if the condition evaluates to false.

On the other hand, do while loops check the condition after the loop has already been executed. The loop will always run at least once even if the condition evaluates to false. The do while loop syntax is split into two parts: the ‘do‘ part and the ‘while‘ part. The ‘do‘ part tells the loop what code to run and the ‘while‘ part specifies the condition that will be tested. The ‘while‘ part comes after the ‘do‘ part. Do while loops do not have an in-built counter but you can include a counter in the loop.

Watch the video below and then scroll down to see the sample code.

Sample PHP code:

1
2
3
4
5
6
7
8
<?php
 $counter = 0;
 do{
 echo $counter , "</br>";
 $counter++;
 }
 while($counter < 10);
?>

PHP Manual references:

Switch statements in PHP

This tutorial explains how to use switch statements in the PHP language. Switch statements can have a number of possible execution paths, unlike if, else and else if statements. Switch statements can be used to test different conditions for a single variable and can be more efficient to write than if, else and else if statements.

If you find you are writing several if, else if, and else statements and you find your code is getting a little messy, then using a switch statement might be the cleaner, neater, and more efficient way to go.

 

A switch statement involves multiple cases that can be tested for a variable as well as a default case if no other conditions (cases) are met. Each case also has a break statement which means if the condition from one case is met, then the switch statement will end and none of the other cases will be tested. To see how to use switch statements in PHP, you can watch the video below or scroll down to see the sample code.

PHP Sample code:

Note how the break; statement is used below. When used, it can stop checking all other cases once a test case evaluates to true. It is optional and if left out, the program will continue to check all other cases and run their code if they evaluate to true, until the switch statement ends.

<?php
 
 $day = 300;
 
 switch($day){
 case 1:
 echo "Monday";
 break;
 
 case 2:
 echo "Tuesday";
 break;
 
 case 3:
 echo "Wednesday";
 break;
 
 case 4:
 echo "Thursday";
 break;
 
 case 5:
 echo "Friday";
 break;
 
 /* 
 Break statement is optional - when it is executed, it will stop
 the switch statement from running
 */
 
 // The default case is also optional.
 
 default:
 echo "Not a weekday";
 break;
 }
 
 
?>

PHP Manual references:

Else and else if statements in PHP

In the previous tutorial we looked at if statements in PHP. In this tutorial we will look at how to specify more conditions by using the else and else if statements. If you are testing multiple conditions you can use an if statement along with else if and else statements. You can also place an if statement inside another if statement – this is known as a nested if statement.

The basic structure of if, else if and else statements looks like this:

if(condition){
  // do something
}
else if(another condition){
  // do something else
}
else{
  // do something completely different if the
  // other two conditions are not met
}

The basic structure of a nested if statement looks like this:

if(condition){
  if(another condition){
     //do something
  }
}

Make sure you use the correct brackets for conditions and statements inside if statements, and also make sure that you have matching closing brackets.

Watch the video below to see how to use if, else if, and else statements in PHP and then scroll down to see the sample code.

Sample PHP code:

<?php
 
 $age = 20;
 
 if($age >= 18){
 echo "You are old enough to vote";
 }
 
 else if($age == 17){
 echo "You can vote on your next birthday";
 }
 
 else{
 echo "You are not old enough to vote";
 }
 
?>

PHP Manual references:

If statements in PHP

If statements (conditional statements) are used to make decisions in your programs. An if statement will test a condition and then run a section of code if the condition evaluates to true. There are a number of relational operators and logical operators you can use in if statements to test different conditions which are explained in the video below.

Relational operators

Relational operators are used for comparison such as checking if one variable’s value is greater than another. Eg. is x greater than y? (x>y). Here is a list of relational operators:

Operator Description
< less than
> greater than
<= less than or equal to
>= greater than or equal to
== equal to
=== identical to (equal to AND of the same data type)
!= not equal to
!== not identical to (not equal to AND not of the same data type)

Logical operators

Logical operators are used to combine conditions. Eg. is x greater than both y and also less than z? Here is a list of logical operators:

Operator Description
&& AND
|| OR
and AND (same as &&)
or OR (same as ||)
xor Xor (if either one or the other is true, but not both)
! NOT (eg. !$x returns true if $x is not true)

Watch the video and then scroll down to see the sample code.

Sample if statement PHP code:

<?php
 
 $number = 5;
 
 if($number < 10)
 {
 echo $number , " is less than 10";
 }
 
// comparison operators include < (less than), > (greater than), <= (less than or equal to), >= (greater than or equal to), == (equal to), != (not equal to), and === (identical to).
?>

Sample PHP code using AND operator used to test that both criteria are true (the AND operator is two && ampersands):

<?php
 
 $number = 5;
 
 if($number > 1 && $number < 10)
 {
 echo $number , " is greater than 1 and less than 10.";
 }
 
 // logical operators include && (and) and || (or)
?>

Sample PHP code using OR operator to test that at least one criteria is true. (the OR operator is two || bars):

<?php
 
 $number = 5;
 
 if($number < 10 || $number > 20)
 {
 echo $number , " is less than 10 or greater than 20.";
 }
 
 // logical operators include && (and) and || (or)
?>

PHP Manual references:

Conditional statements in C#

Conditional statements

Conditional statements are used so that your program can make decisions. When your program has a range of conditions, you can build powerful algorithms. In this tutorial, you will learn about if statements, if/else statements, and if/else if statements. Watch the video below and then scroll down to see the sample code.

if statements

The most basic type of conditional statement is the if statement. The if statement basically works like this: if something is true, then do this. The basic syntax looks like this:

if( <condition>)
{
// do something
}

The condition goes inside the ( and ) brackets. The action that will occur (if the condition evaluates to true) goes inside the { and } brackets. For example, to say the message “Hello World” only if the value of x is greater than 10, you would use the following code:

if(x>10)
{
 print("Hello World");
}

In the code above, the condition is to check whether x is greater than 10. As an example, if the value of x was 11, then the message “Hello world” would be displayed. If the value of x was 9, then nothing would happen. If the value x was exactly 10, nothing would happen because the value of x needs to be greater than 10 for the message to be displayed.

if/else statement

Regular if statements are easy to use. However, they don’t specify what the program should do if the condition evaluates to false. if/else statements allow you to specify what action will occur when a condition evaluates to true and also what will occur if the condition evaluates to false. This is known as a binary selection structure.

The if/else statement basically reads as “if something is true, then do this, otherwise do this other thing”. The syntax looks like this:

if(<condition>)
{
// do something
}

else
{
// do something else
}

Here is an example of a basic if/else statement that will display a message based on someone’s age stored in an ‘age’ variable.

if(age>=18)
{
 print("You are old enough to vote");
}
else
{
 print("You are not old enough to vote");
}

if/else if statement

The limitation of the if/else statement is that it only allows two possible paths. What if you want your program to be able to go down many different paths? What if you have many different conditions you want to check? That is where the if/else if statement comes in.

The if/else if statement provides more options than the if/else statement. It is set up in the same way but it has more than one condition. The else part is optional in an if/else if statement.

Here is some sample code for the if/else if statement:

if(age>=18)
{
 print("You are old enough to vote");
}
else if(age==17)
{
 print("You can vote after your next birthday");
}
else
{
 print("You are not old enough to vote");
}

Nested If Statements

The sample code below shows how to use if statements inside other if statements (nested if statements). The video here explains all about nested if statements!

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 var age = 21;
 var maxAge = 30;
 var minAge = 18;
 
 // Below is an example of using if statements inside other if statements
 // This is called nested if statements.
 
 if(age>=minAge){
 if(age<=maxAge){
 document.write("You are within the accepted age range.");
 }
 else{
 document.write("You are above the accepted maximum age.");
 }
 }
 else{
 document.write("You are under the accepted minimum age.");
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

If else statements

Often when using if statements, you will want to test more than just one condition. The sample code below explains how to do this. You can also watch the video here which runs through using if, else if, and else statements.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Else Statements</title>
 <script type="text/javascript">
 
 // You can have a single if statement (tests one condition)...
 // However, you can also have an IF statement that tests multiple conditions
 // Eg. You can have an if and an else statement (tests two conditions)
 // You can have an if statement, else if statements, and an else statement (tests several conditions)
 
 // if - is the first condition to test
 // else if - is used to test other conditions
 // else - will run a piece of code only if none of the other condition tests have evaluated to true
 
 var age = 16
 
 if(age>=18){
 document.write("You are old enough to vote.");
 }
 else if(age==17){
 document.write("You can vote after your next birthday.");
 }
 else{
 document.write("You cannot vote yet.");
 }
 
 // Make sure you don't confuse the = sign (used for assigning values to variables) for == (used for comparisons)
 
 </script>
 
</head>
<body>
 
</body>
</html>

If statements

An ‘if statement’ is used to test a condition. If the test condition evaluates to true (Eg. x is less than y), then the code inside the if statement will run. If the test condition evaluates to false, then the code inside the if statement won’t run and the program will continue on. Take a look at the video here which explains if statements, and then try using the sample code below.

<!DOCTYPE html>
<html lang="en"
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Statements</title>
 <script type="text/javascript">
 
 /* For an 'if' statement, the syntax should look like:
 
 if(condition to be tested){
 //run code here
 }
 
 */
 
 var age = 20 // declare the variable age
 
 if(age>=18){
 document.write("You are old enough to vote."); // this message only displays if age is greater than or equal to 18
 }
 
 /* Operators you can use include:
 == equal to
 != not equal to
 > greater than
 < less than
 >= greater than or equal to
 <= less than or equal to
 */
 
 </script>
 
</head>
<body>
 
</body>
</html>

Switch Statements in JavaScript

Switch statements are similar to ‘If’ statements but they are neater when working with many conditions. This video tutorial explains how to use switch statements. View it below or click here to view it on YouTube.

A switch statement is like an IF statement but is neater when working with many conditions.

Make sure you use the break statement at the end of each case so that the code runs efficiently. If you don’t use the break statement, the program will keep checking through all conditions even if a match has already been found. If none of the conditions are met, then the default case will run.

Take a look at the source code below and try using it in your own program.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Switch Statements</title>
 <script type="text/javascript">
 
 // A switch statement is like an IF statement but is neater when working with many conditions.
 // Use the break statement at the end of each case so that the code runs efficiently.
 // If you don't use break, the program which keep checking through all conditions even if a match has
 // already been found. If none of the conditions are met, then the 'default' case will run.
 
 var city="Sydney";
 
 switch(city){
 case "Melbourne":
 document.write("You are from Melbourne");
 break;
 case "Sydney":
 document.write("You are from Sydney");
 break;
 case "Perth":
 document.write("You are from Perth");
 break;
 case "Brisbane":
 document.write("You are from Brisbane");
 break;
 default:
 document.write("You don't live in a city I recognise.");
 }
 
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: While loops

Using AND/OR operators in ‘If’ statements with JavaScript.

You can specify more than one condition in an IF statement. You can specify whether several conditions must evaluate to true for code to run or whether one of several possible conditions must evaluate to true for code to run. This involves using AND and OR operators. The AND operator in JavaScript is && and the OR operator in JavaScript is II. The NOT operator is a single ! (exclamation mark).

You can watch the video below or click here to view it on YouTube. Make sure you also have a look at the sample code further below and feel free to use and modify it.

So after watching the video, let’s recap what logical operators are all about. Using logical operators such as and/or allow a programmer to write complex if statements. For example, you can check if a number is greater than 10 AND is also less than 20 (both conditions have to evaluate to true for the code to run inside the if statement). Or, you can check if a number is less than 5 OR greater than 10 (only one condition has to evaluate to true for the code to run inside the if statement)

Logical operators:

  • The symbols && are used for the and operator in JavaScript
  • The || symbols are used for the or operator in JavaScript
  • A single exclamation mark ! can also be used as a not operator.

Check out the sample code below to see how these logical operators can be used to form complex if statements in JavaScript.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 // This is a better way than using nested if statements
 // You can use and/or operators in JS (known as logical operators)
 // The AND operator is &&
 // The OR operator is ||
 
 var firstName = "John";
 var lastName = "Smith";
 
 if(firstName=="John" && lastName=="Smith"){
 document.write("Hello, John Smith!");
 // The message above will only be displayed if firstName is John AND lastName is Smith.
 // Try using || instead of && and change the value of one of the variables. What happens?
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Switch statements

Nested ‘If’ Statements in JavaScript

This tutorial explains how to create nested IF statements in JavaScript. A nested IF statement is an IF statement that is inside another IF statement. Also known as…ifception 😉 Using nested IF statements is not always the best way to code but it is handy to know them anyway. View the video below or click here to watch it on YouTube.

You can also view the previous tutorial on ‘if’ statements and see which operators can be used in JavaScript here.

The sample code below shows how to use if statements inside other if statements (nested if statements).

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Nesting If Statements</title>
 <script type="text/javascript">
 
 var age = 21;
 var maxAge = 30;
 var minAge = 18;
 
 // Below is an example of using if statements inside other if statements
 // This is called nested if statements.
 
 if(age>=minAge){
 if(age<=maxAge){
 document.write("You are within the accepted age range.");
 }
 else{
 document.write("You are above the accepted maximum age.");
 }
 }
 else{
 document.write("You are under the accepted minimum age.");
 }
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Using and/or operators in a complex If statement

‘If’ Statements in JavaScript

This tutorial explains how to use IF statements for conditional programming in JavaScript. An IF statement can be used to make decisions based on whether a condition evaluates to true or false. Watch the video below or click here to view it on YouTube.

An ‘if statement’ is used to test a condition. If the test condition evaluates to true (Eg. x is less than y), then the code inside the if statement will run. If the test condition evaluates to false, then the code inside the if statement won’t run and the program will continue on.

Operators that you can use in JavaScript to make comparisons include:

Equal to ==
Not equal to !=
Greater than >
Less than <
Greater than or equal to >=
Less than or equal to <=

Take a look at the sample code of an if statement below.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Statements</title>
 <script type="text/javascript">
 
 /* For an 'if' statement, the syntax should look like:
 
 if(condition to be tested){
 //run code here
 }
 
 */
 
 var age = 20 // declare the variable age
 
 if(age>=18){
 document.write("You are old enough to vote."); // this message only displays if age is greater than or equal to 18
 }
 
 /* Operators you can use include:
 == equal to
 != not equal to
 > greater than
 < less than
 >= greater than or equal to
 <= less than or equal to
 */
 
 </script>
 
</head>
<body>
 
</body>
</html>

Often when using if statements, you will want to test more than just one condition. The sample code below explains how to do this.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - If Else Statements</title>
 <script type="text/javascript">
 
 // You can have a single if statement (tests one condition)...
 // However, you can also have an IF statement that tests multiple conditions
 // Eg. You can have an if and an else statement (tests two conditions)
 // You can have an if statement, else if statements, and an else statement (tests several conditions)
 
 // if - is the first condition to test
 // else if - is used to test other conditions
 // else - will run a piece of code only if none of the other condition tests have evaluated to true
 
 var age = 16
 
 if(age>=18){
 document.write("You are old enough to vote.");
 }
 else if(age==17){
 document.write("You can vote after your next birthday.");
 }
 else{
 document.write("You cannot vote yet.");
 }
 
 // Make sure you don't confuse the = sign (used for assigning values to variables) for == (used for comparisons)
 
 </script>
 
</head>
<body>
 
</body>
</html>

Next tutorial: Nested if statements