Introduction to Comparisons

If a Condition Exists

A comparison is an operation that examines the relationship between two values (or two objects). As is the case for all C-based languages, the primary operator to use is named if. The primary formula to use it is:

if( expression ) {
	statement;
}

In the parentheses of if(), create an expression-based comparison. Inside the curly brackets, create one or more statements that will execute.

Boolean Operators

A Boolean operator is an operator used to compare two values. JavaScript primarily supports the operators of the C language, some of them with slight modifications.

Practical LearningPractical Learning: Introducing Conditional Statements

  1. Start Microsoft Visual Studio
  2. On the main menu, click File -> New -> Project...
  3. In the New Project dialog box, click ASP.NET Web Application (.NET Framework). Change project Name to CableCompany4
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the MVC icon
  6. Click OK
  7. To create a new CSS file, in the Solution Explorer, right-click Content -> Add -> New Item...
  8. In the left frame of the Add New Item dialog box, click Web and click Markup under it. In the middle frame, click Style Sheet
  9. Change the file Name to CableCompany
  10. Click Add
  11. Change the document as follows:
    body {
        background-color: white;
    }
    
    form                        { padding: 1em;
                                  margin:           auto;
                                  width:            550px;
                                  background-color: #e0d4c0;
                                  border:           1px solid maroon; }
    form div                    { padding:          4px;
                                  margin:           0 0 1px 0; }
    input[type=number]          { width:            80px;
                                  float:            right;
                                  border:           1px solid maroon; }
    input[type=number]:focus    { outline:          1px solid #ff6a00; }
    input[type=button]          { border:           0;
                                  border-radius:    10px;
                                  font-size:        14px;
                                  width:            130px;
                                  margin-left:      100px;
                                  background-color: brown;
                                  padding:          0.75em;
                                  color:            yellow; }
    input[type=button]:hover    { color:            white;
                                  cursor:           pointer;
                                  background-color: chocolate; }
    form > fieldset > div > div { margin:           0 0 5px 0; }
    .bold                       { font-weight:      600;       }
    .main-title                 { font-family:      'Times New Roman', Garamond, Georgia, serif;
                                  color:            maroon; }
    .caption                    { width:            11.45em;
                                  display:          table-cell; }
    .resulting-value            { width:            6em;
                                  background-color: white;
                                  display:          table-cell;
                                  border:           1px solid maroon; }
  12. In the Solution Explorer, right-click CableCompany4 and click Manage NuGet Packages...
  13. Click the Browser button.
    Do a search on angularjs (you must be connected to the Internet)
  14. In the list, click angularjs:

    Microsoft Visual Studio - AngularJS Installation

  15. In the middle-right frame, click Install. If a dialog box comes up, read it and click OK:

    Preview

  16. In the Solution Explorer, right-click Scripts -> Add -> New Item...
  17. In the left frame of the Add New Item dialog box, click Web and, in the middle frame, click JavaScript File
  18. Change the Name of the file to BillPreparation
  19. Click Add
  20. Change the document as follows:
    var appCableCompany = angular.module('appCableCompany', []);
    appCableCompany.controller("BillsController", function () {
        this.estimateCableBill = function () {
            var packageFee = 26.58;
            var dvr = this.DVRService;
            var sport = this.SportsPackage;
    
            var subTotal = packageFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
    
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.localTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  21. In the Solution Explorer, expand App_Start and double-click BundleConfig.cs
  22. Change the document as follows:
    using System.Web;
    using System.Web.Optimization;
    
    namespace CableCompany4
    {
        public class BundleConfig
        {
            // For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
            public static void RegisterBundles(BundleCollection bundles)
            {
                bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                            "~/Scripts/jquery-{version}.js",
                            "~/Scripts/angular.js",
                            "~/Scripts/BillPreparation.js"));
    
                bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                            "~/Scripts/jquery.validate*"));
    
                // Use the development version of Modernizr to develop with and learn from. Then, when you're
                // ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
                bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
                            "~/Scripts/modernizr-*"));
    
                bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                          "~/Scripts/bootstrap.js"));
    
                bundles.Add(new StyleBundle("~/Content/css").Include(
                          "~/Content/bootstrap.css",
                          "~/Content/site.css",
                          "~/Content/CableCompany.css"));
            }
        }
    }
  23. In the Solution Explorer, click the button on the left of Views to expand it. In the same way, expand the Shared folder
  24. Under Shared, double-click _Layout.cshtml to open it
  25. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>ESCAPE - Bill Evaluation :: @ViewBag.Title</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    @Html.ActionLink("ESCAPE", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
                </div>
                <div class="navbar-collapse collapse">
                    <ul class="nav navbar-nav">
                        <li>@Html.ActionLink("Bill Evaluation", "BillEvaluation", "Home")</li>
                        <li>@Html.ActionLink("About", "About", "Home")</li>
                        <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="container body-content">
            @RenderBody()
            <hr />
            <footer>
                <p class="text-center">&copy; @DateTime.Now.Year - ESCAPE (Eastern Shore Company and Production Entertainment)</p>
            </footer>
        </div>
    
        @Scripts.Render("~/bundles/jquery")
        @Scripts.Render("~/bundles/bootstrap")
        @RenderSection("scripts", required: false)
    </body>
    </html>
  26. In the Solution Explorer, click the button on the left of Controllers to expand it
  27. Under Controllers, double-click HomeController.cs to open it
  28. Add a method named BillEvaluation as follows:
    using System.Web.Mvc;
    
    namespace CableCompany4.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            public ActionResult About()
            {
                ViewBag.Message = "Your application description page.";
    
                return View();
            }
    
            public ActionResult Contact()
            {
                ViewBag.Message = "Your contact page.";
    
                return View();
            }
    
            public ActionResult BillEvaluation() => View();
        }
    }
  29. In the class, right-click inside the BillEvaluation() method and click Add View...
  30. In the dialog box, make sure the text box displays BillEvaluation and click Add
  31. Change the document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <table class="tbl-package">
                        <tr>
                            <td style="width: 175px"><label for="Basic">Basic</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Basic" value="Basic"
                                        ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Standard">Standard</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Standard" value="Standard"
                                        ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Performance">Performance</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Performance" value="Performance"
                                        ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                    </table>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Local Taxes:</span>
                        <span class="resulting-value">{{pay.localTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  32. To execute, on the main menu, click Debug -> Start Without Debugging:

    Introduction to Conditional Statements

  33. Click one of the radio buttons. Here is an example:

    Introduction to Conditional Statements

  34. Click DVR Service and type 27.96
  35. Click Sports Package and type 7.34

    Introduction to Conditional Statements

  36. Close the browser and return to your programming environment

A Comparison for Equality

To find out if two values are the same, create an expression that separates them with the === operator.. You can compare a variable to a value to find out whether the variable holds the value to which it is being compared. You can perform the comparison on numeric values. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Employment Summary: {{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var employeeId = 24;

        if (employeeId === 24) {
            this.conclusion = "Welcome Mrs. Landford, you will now be redirected to a classified document created 'for your eyes only'. As the system is monitoring all activities on the document, please don't make any copy of the document and don't send it to anybody.";
        }
    });
</script>
</body>
</html>

In the same way, you can perform a comparison on strings. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Employment Summary: {{ec.conclusion}}</p>
    </div>
</section>
<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var status = "Full Time";

        if (status === "Full Time") {
            this.conclusion = "Full Benefits";
        }
    });
</script>
</body>
</html>

JavaScript also accepts the == operator used by the other C-based languages.

A Comparison for Inequality

To find out if two values are not equality, use the !== operator in an expression. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Employment Summary: {{ec.conclusion}}</p>
    </div>
</section>
<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var status = "Part Time";

        if (status !== "Full Time") {
            this.conclusion = "Basic Benefits";
        }
    });
</script>
</body>
</html>

You can also use the != operator of the other C-based languages.

A Comparison for Lower Value

To find out if one value is lower than another value, include them in an expression and separate them with the < operator. The comparison is primarily performed on numbers. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Classroom Summary: {{ec.conclusion}}</p>
    </div>
</section>
<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var capacity = 35;

        if (capacity < 55) {
            this.conclusion = "55 students had registered for the course but Room 102 classroom can accomodate only fewer people.";
        }
    });
</script>
</body>
</html>

The < operation can also be performed on strings. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Countries Statistics: {{ec.conclusion}}</p>
    </div>
</section>
<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var pais = "Zambia";
        var country = "Zimbabwe";

        if (pais < country) {
            this.conclusion = "Zimbabwe comes before Zambia";
        }
    });
</script>
</body>
</html>

When the comparison is made on strings, the interpreter will check the rules of the language of the computer used by your visitor. The interpreter will compare the characters of each string by the positions of the characters.

The Comparison for a Lower or Equal Value

To combine the comparions for equality and lower values, use the <= operator. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>Employment Summary: {{ec.conclusion}}</p>
    </div>
</section>
<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var yearlySalary = 40000;

        if (yearlySalary <= 50000) {
            this.conclusion = "The employment candidate will not accept a salary lower than $50,000 a year.";
        }
    });
</script>
</body>
</html>

The Comparison for Greater Value

To find out if one value is greater than another, use the > operator.

The Comparison for Greater or Equal Value

To find out if one value is greater than or equal to another, use the >= operator.

A Boolean Value

Introduction

A value is said to be Boolean if it can hold one of two values: true or false. Any of the Boolean expressions we have used so far represented or produced a Boolean value.

A Boolean Variable

A Boolean value is one that can be expressed as being true or false. In AngularJS and JavaScript, to get such a value, declare it with the var keyword. You can then initialize the variable with true or false. Here is an example:

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var isFullTime = true;
    });
</script>

You can also initialize the variable using a Boolean expression. Here is an example:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Exercise</title>
</head>
<body>
    <script src="Scripts/angular.js"></script>

    <section ng-app="appExercise">
        <div ng-controller="ExerciseController as ec">
            <p>Employment Summary: {{ec.conclusion}}</p>
        </div>
    </section>
    <script type="text/javascript">
        var appExercise = angular.module("appExercise", []);
        appExercise.controller("ExerciseController", function () {
            var status = "Full Time";
            var isFullTime = status == "Full Time";

            if (isFullTime === true) {
                this.conclusion = "Full Benefits";
            }
        });
    </script>
</body>
</html>

To make your code easier to read, you should put the Boolean expression in parentheses. Here is an example:

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var status = "Full Time";
        var isFullTime = (status == "Full Time");

        if (isFullTime === true) {
            this.conclusion = "Full Benefits";
        }
    });
</script>

What Other Alternative

A conditional statement created with if is used to examine one possibility. Sometimes there are other possible outcomes. To let you examine any possibility other than the one from if, the C-based languages provide the else keyword. It is used to create a section after the if clause. The formula to follow is:

if( condition) {
    if-statement(s);
} else { else-statement(s) }

As you can see, the else section section doesn't need a condition; this is because it is made for any situation that doesn't fit the if condition. Instead, the else clause must include its own statement. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>{{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var employeeId = 293584;

        if (employeeId === 24) {
            this.conclusion = "Welcome Mrs. Landford, you will now be redirected to a classified document created 'for your eyes only'. As the system is monitoring all activities on the document, please don't make any copy of the document and don't send it to anybody.";
        } else {
            this.conclusion = "You are not allowed to view classified information. If you have any question, please contact our administration.";
        }
    });
</script>
</body>
</html>

By the way, you can write the else on its own line or on many lines thereafter.

What Other Alternatives

As mentioned already, an if condition examines only one outcome. There can be many situations other than that first condition. To let you consider them, the C-based languages provide a condition expressed with else if. The formula to follow is:

if( if-condition) {
    if-statement(s);
} else if( else-if-condition) { else-if-statement(s); }

Based on this, create an expression with else if() after the if() condition. The else if() clause must include its own condition in its parentheses. In its square brackets, create one or more statements. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>{{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var classification = "Secret";

        if (classification === "Secret") {
            this.conclusion = "A classified document labeled Secret is for high level personnel. If exposed to public use, such a document can cause 'serious damage' to the nation.";
        } else if (classification === "Confidential") {
            this.conclusion = "A document is classified as Confidential if its publication may significant damage to national security.";
        }
    });
</script>
</body>
</html>

A Last Recourse Alternative

The if() clause and an else if() condition examine only one outcome each. In most cases, you may still have at least one situation that don't fit neither the if() nor the else if() condition. In this case, you can add a last else clause that embraces all the other conditions. The formula to follow is:

if( if-condition) {
    if-statement(s);
} else if( else-if-condition_1) {
    else-if-statement(s)_1;
} else {
    else-statement(s)_n;
}

The else clause must be created last.

Practical LearningPractical Learning: Creating a Conditional Statement

  1. Click the BillPreparation.js tab and change the document as follows:
    var appCableCompany = angular.module('appCableCompany', []);
    appCableCompany.controller("BillsController", function () {
        this.estimateCableBill = function () {
            var packageFee = 0.00;
            var dvr = this.DVRService;
            var sport = this.SportsPackage;
            var category = this.packageType;
    
            if (category == 'Standard') {
                packageFee = 34.50;
            }
            else if (category == 'Performance') {
                packageFee = 51.85;
            }
            else {
                packageFee = 29.25;
            }
    
            var subTotal = packageFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
    
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.localTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  2. Click the BillEvaluation.cshtml tab to activate it and change it as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <table class="tbl-package">
                        <tr>
                            <td style="width: 175px"><label for="Basic">Basic</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Basic" value="Basic"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Standard">Standard</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Standard" value="Standard"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Performance">Performance</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Performance" value="Performance"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                    </table>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Local Taxes:</span>
                        <span class="resulting-value">{{pay.localTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  3. To execute, press Ctrl + F5
  4. Click each of the radio buttons:

    An Else Conditional Statement

    An Else Conditional Statement

    An Else Conditional Statement

  5. Click DVR Service and type 6.92
  6. Click Sports Package and type 7.58

    An Else Conditional Statement

  7. Click the Basic radio button:

    An Else Conditional Statement

  8. Click the Standard radio button:

    An Else Conditional Statement

  9. Close the browser and return to your programming environment

Considering Two Alternatives to a Condition

An else if() condition is used to examine one outcome. If you want to consider more than one situation, add another else if() clause. The formula to follow is:

if( if-condition) {
    if-statement(s);
} else if( else-if-condition_1) {
    else-if-statement(s)_1;
} else if( else-if-condition_2) {
    else-if-statement(s)_2;
}

In this case, each else if() includes its own condition and one or more statements. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>{{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var classification = "Top Secret";

        if (classification === "Top Secret") {
            this.conclusion = "A Top Secret document requires the highest level of security. Such a document can cause exceptional damage to a large number of administration employees and to the country as a whole.";
        } else if (classification === "Secret") {
            this.conclusion = "A classified document labeled Secret is for high level personnel. If exposed to public use, such a document can cause 'serious damage' to the nation.";
        } else if (classification === "Confidential") {
            this.conclusion = "A document is classified as Confidential if its publication may significant damage to national security.";
        }
    });
</script>
</body>
</html>

In this case, if you want to consider an alternative that fits neither the if() condition nor one of the other two else if() clauses, add a last else section.

Practical LearningPractical Learning: Considering Two Alternatives

  1. Click the BillPreparation.js tab and change the document as follows:
    var appCableCompany = angular.module('appCableCompany', []);
    appCableCompany.controller("BillsController", function () {
        this.estimateCableBill = function () {
            var packageFee = 0.00;
            var dvr = this.DVRService;
            var additionalBoxesFee = 0.00;
            var sport = this.SportsPackage;
            var category = this.packageType; // 10 Channels, Standard (140 Channels), Performance (220)
            var boxes = this.numberOfBoxes;
    
            if (category == 'Standard') {
                packageFee = 34.50;
            }
            else if (category == 'Performance') {
                packageFee = 51.85;
            }
            else {
                packageFee = 29.25;
            }
    
            if (boxes == 1) {
                additionalBoxesFee = 15.27;
            } else if (boxes == 2) {
                additionalBoxesFee = 2 * 12.93;
            } else if (boxes == 3) {
                additionalBoxesFee = 3 * 10.46;
            } else { // if (boxes >= 4)
                additionalBoxesFee = boxes * 9.97;
            }
    
            var subTotal = packageFee + additionalBoxesFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
    
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.localTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  2. Click the BillEvaluation.cshtml tab and change the document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <table class="tbl-package">
                        <tr>
                            <td style="width: 175px"><label for="Basic">Basic</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Basic" value="Basic"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Standard">Standard</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Standard" value="Standard"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Performance">Performance</label></td>
                            <td class="text-left">
                                <input type="radio" name="rdoPackageType" id="Performance" value="Performance"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                    </table>
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                    <div>
                        <label for="nbrOfBoxes">Number of Boxes:</label>
                        <input type="number" id="nbrOfBoxes" ng-model="pay.numberOfBoxes"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        &nbsp;
                    </div>
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Local Taxes:</span>
                        <span class="resulting-value">{{pay.localTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  3. To execute the application, on the main menu, click Debug -> Start Without Debugging
  4. Click DVR Service and type 9.27

    Text Box

  5. Click Sports Package and type 7.95
  6. Click Number of Boxes and type 1

    Text Box

  7. Click the Standard radio button:

    Label

  8. Change the Number of Boxes to 3

    Text Box

  9. Close the browser and return to your programming environment

Considering Different Outcomes

You can create as many else if() clauses as you want, each with its own condition and its one or more statements. The formula to follow is:

if( if-condition) {
    if-statement(s);
}
else if( else-if-condition_1) {
    else-if-statement(s)_1;
}
else if( else-if-condition_2) {
    else-if-statement(s)_2;
}
. . .
else if( else-if-condition_n) {
    else-if-statement(s)_n;
}

Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>{{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var classification = "Confidential";

        if (classification === "Top Secret") {
            this.conclusion = "A Top Secret document requires the highest level of security. Such a document can cause exceptional damage to a large number of administration employees and to the country as a whole.";
        } else if (classification === "Secret") {
            this.conclusion = "A classified document labeled Secret is for high level personnel. If exposed to public use, such a document can cause 'serious damage' to the nation.";
        } else if (classification === "Confidential") {
            this.conclusion = "A document is classified as Confidential if its publication may significant damage to national security.";
        } else if (classification === "Restricted") {
            this.conclusion = "A document is Restricted if its publication may create unexpected situations or consequences.";
        }
    });
</script>
</body>
</html>

The if() clause and each else if() condition examine only one outcome each. In most cases, you may still have a situation that don't fit neither the if() nor any of the else if() conditions. In this case, you can add a last else clause that embraces all the other conditions. The formula to follow is:

if( if-condition) {
    if-statement(s);
} else if( else-if-condition_1) {
    else-if-statement(s)_1;
} else if( else-if-condition_2) {
    else-if-statement(s)_2;
} else if( else-if-condition_n) {
    else-if-statement(s)_n;
} else {
    else-statement(s)_n;
}

The else clause must be created last. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Exercise</title>
</head>
<body>
<script src="Scripts/angular.js"></script>

<section ng-app="appExercise">
    <div ng-controller="ExerciseController as ec">
        <p>{{ec.conclusion}}</p>
    </div>
</section>

<script type="text/javascript">
    var appExercise = angular.module("appExercise", []);
    appExercise.controller("ExerciseController", function () {
        var classification = "Clearance";

        if (classification === "Top Secret") {
            this.conclusion = "A Top Secret document requires the highest level of security. Such a document can cause exceptional damage to a large number of administration employees and to the country as a whole.";
        } else if (classification === "Secret") {
            this.conclusion = "A classified document labeled Secret is for high level personel. If exposed to public use, such a document can cause 'serious damage' to the nation.";
        } else if (classification === "Confidential") {
            this.conclusion = "A document is classified as Confidential if its publication may significant damage to national security.";
        } else if (classification === "Restricted") {
            this.conclusion = "A document is Restricted if its publication may create unexpected situations or consequences.";
        } else {
            this.conclusion = "A document that is not officially classified, also referred to as 'Unclassified', may be made availability for public use.";
        }
    });
</script>
</body>
</html>

Practical LearningPractical Learning: Considering Different Outcomes

  1. Click the BillPreparation.js tab and change the document as follows:
    var appCableCompany = angular.module('appCableCompany', []);
    appCableCompany.controller("BillsController", function () {
        this.estimateCableBill = function () {
            var accountFee = 0.00;
            var packageFee = 0.00;
            var additionalBoxesFee = 0.00;
            var dvr = this.DVRService;
            var sport = this.SportsPackage;
            var category = this.packageType; // 10 Channels, Standard (140 Channels), Performance (220)
            var boxes = this.numberOfBoxes;
            var accountType = this.acntCategory;
    
            if (category === 'Standard') {
                packageFee = 34.50;
            }
            else if (category === 'Performance') {
                packageFee = 51.85;
            }
            else {
                packageFee = 29.25;
            }
    
            if (boxes === 1) {
                additionalBoxesFee = 15.27;
            } else if (boxes === 2) {
                additionalBoxesFee = 2 * 12.93;
            } else if (boxes === 3) {
                additionalBoxesFee = 3 * 10.46;
            } else { // if (boxes >= 4)
                additionalBoxesFee = boxes * 9.97;
            }
    
            if (accountType === "smallBusiness") {
                accountFee = 6.55 * boxes;
            } else if (accountType === "hospital") {
                accountFee = 2.55 * boxes;
            } else if (accountType === "government") {
                accountFee = 8.55 * boxes;
            } else if (accountType === "hotel") {
                accountFee = 12.86 * boxes;
            } else { // if (accountType === "Home/Residential")
                accountFee = 9.92 * boxes;
            }
    
            var subTotal = packageFee + accountFee + additionalBoxesFee + dvr + sport;
            var fcc = subTotal * 0.00250881;
            var local = (subTotal + fcc) * 0.0372668;
            var state = (subTotal + fcc) * 0.0082493;
            
            this.fccFee = fcc;
            this.DVRService = dvr;
            this.localTaxes = local;
            this.stateTaxes = state;
            this.subTotal = subTotal;
            this.SportsPackage = sport;
            this.boxesFee = additionalBoxesFee;
            this.feeBasedOnAccount = accountFee;
            this.CableTVPackageFee = packageFee;
            this.paymentAmount = subTotal + fcc + local + state;
        }
    });
  2. Click the BillEvaluation.cshtml tab and redesign the whole document as follows:
    @{
        ViewBag.Title = "Bill Evaluation";
    }
    
    <h1 class="text-center main-title bold">Eastern Shore Company and Production Entertainment</h1>
    <h2 class="text-center main-title bold">Bill Evaluation</h2>
    
    <form name="BillEvaluation" method="post" ng-app="appCableCompany">
        <fieldset ng-controller="BillsController as pay">
            <legend>Cable TV Services</legend>
    
            <div class="row">
                <div class="col-md-6">
                    <div class="bold">Cable TV Package Type</div>
                    <table>
                        <tr>
                            <td style="width: 175px"><label for="Basic">Basic</label></td>
                            <td class="medium">
                                <input type="radio" name="rdoPackageType" id="Basic" value="Basic"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Standard">Standard</label></td>
                            <td>
                                <input type="radio" name="rdoPackageType" id="Standard" value="Standard"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="Performance">Performance</label></td>
                            <td>
                                <input type="radio" name="rdoPackageType" id="Performance" value="Performance"
                                       ng-model="pay.packageType" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                    </table>
                </div>
    
                <div class="col-md-6">
                    <div class="bold">Account Category</div>
                    <table>
                        <tr>
                            <td style="width: 180px"><label for="home">Home</label></td>
                            <td class="medium">
                                <input type="radio" name="rdoAccountCategory" id="home" value="home"
                                       ng-model="pay.acntCategory" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="hotel">Hotel</label></td>
                            <td>
                                <input type="radio" name="rdoAccountCategory" id="hotel" value="hotel"
                                       ng-model="pay.acntCategory" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="hospital">Hospital</label></td>
                            <td>
                                <input type="radio" name="rdoAccountCategory" id="hospital" value="hospital"
                                       ng-model="pay.acntCategory" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="government">Government</label></td>
                            <td>
                                <input type="radio" name="rdoAccountCategory" id="government" value="government"
                                       ng-model="pay.acntCategory" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                        <tr>
                            <td><label for="smallBusiness">Small Business</label></td>
                            <td>
                                <input type="radio" name="rdoAccountCategory" id="smallBusiness" value="smallBusiness"
                                       ng-model="pay.acntCategory" ng-click="pay.estimateCableBill()" />
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div>
                        <label for="DVRService">DVR Service:</label>
                        <input type="number" id="DVRService" ng-model="pay.DVRService"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <label for="SportsPackage">Sports Package:</label>
                        <input type="number" id="SportsPackage" ng-model="pay.SportsPackage"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                </div>
            </div>
            <hr />
            <h3>Additional TV Boxes</h3>
            <div class="row">
                <div class="col-md-6">
                    <div>
                        <label for="nbrOfBoxes">Number of Boxes:</label>
                        <input type="number" id="nbrOfBoxes" ng-model="pay.numberOfBoxes"
                               ng-change="pay.estimateCableBill()" />
                    </div>
                    <div>
                        &nbsp;
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Box(es) Fee:</span>
                        <span class="resulting-value">{{pay.boxesFee | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Category Unit Fee:</span>
                        <span class="resulting-value">{{pay.feeBasedOnAccount | number:2}}</span>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Package Fee:</span>
                        <span class="resulting-value">{{pay.CableTVPackageFee.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Sub-Total:</span>
                        <span class="resulting-value">{{pay.subTotal.toFixed(2)}}</span>
                    </div>
                    <div>
                        <span class="caption bold">FCC Fee:</span>
                        <span class="resulting-value">{{pay.fccFee.toFixed(2)}}</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div>
                        <span class="caption bold">Local Taxes:</span>
                        <span class="resulting-value">{{pay.localTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">State Taxes:</span>
                        <span class="resulting-value">{{pay.stateTaxes | number:2}}</span>
                    </div>
                    <div>
                        <span class="caption bold">Payment Amount:</span>
                        <span class="resulting-value">{{pay.paymentAmount | number:2}}</span>
                    </div>
                </div>
            </div>
        </fieldset>
    </form>
  3. To execute the application, press Ctrl + F5

    Considitional Statements - Considering Different Outcomes

  4. Click DVR Service and type 9.32

    Conditional Statements - Considering Different Outcomes

  5. Click Sports Package and type 7.95
  6. Click Number of Boxes and type 137

    Conditional Statements - Considering Different Outcomes

  7. Click the Standard radio button:

    Conditional Statements - Considering Different Outcomes

  8. Click the Hospital radio button:

    Conditional Statements - Considering Different Outcomes

  9. Click the Hotel radio button

    Conditional Statements - Considering Different Outcomes

  10. Click the Government radio button

    Conditional Statements - Considering Different Outcomes

  11. Close the browser and return to your programming environment

Conditional Conjunctions and Disjunctions

A Boolean Conjunction

A Boolean conjunction consists of combining two conditions that both must be true for the conjunction to be true. If one of both conditions is false, then the whole conjunction is false. To let you create such a situation, the C-based languages use the following operator: &&. The formula to follow is:

condition1 && condition2

Each condition is created as a Boolean expression that uses one of the Boolean operators we saw already.

A Boolean Disjunction

A Boolean disjunction consists of combining two conditions where only one of them has to be true for the whole disjunction to be true. The disjunction is false only if both conditions are false. To let you formulate a disjunction, the C-based languages use the || operator. The formula to follow is:

condition1 || condition2

Once again, each condition is created as a Boolean expression using a Boolean operator.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2017-2019, FunctionX Next