Anonymous Functions

Introduction

An anonymous function is a function that doesn't have a name. To create such a function, use the function keyword, the parentheses, and a body. If you will want to call that function, assign it to a locally declared variable. The formula to follow is:

var variable-name = function(){}

After defining the function, to call it, use the name of the variable and apply the parentheses to it.

Practical LearningPractical Learning: Introducing Operators and Operands

  1. On the main menu of Microsoft Visual Studio, click File -> New -> Project...
  2. In the middle list, click ASP.NET Web Application (.NET Framework) and set the project Name to WaterDistributionCompany2
  3. Click OK
  4. In the New ASP.NET Web Application dialog box, click Empty and click OK
  5. To create a style document, in the Solution Explorer, right-click WaterDistributionCompany2 -> Add -> New Item...
  6. In the left list of the Add New Item dialog box, under Visual C# and under the Web node, click Markup
  7. In the middle list, click Style Sheet
  8. Change the Name to WaterCompany
  9. Click Add
  10. Change the document as follows:
    body {
        background-color: #FFFFFF;
    }
    
    table           { width:       100%;  }
    .bold           { font-weight: bold;  }
    .large          { width:       325px; }
    .txt-format     { width:       80px;  }
    .bill-container { margin:      auto;
                      width:       400px;  }
  11. To create a webpage, in the Solution Explorer, right-click WaterDistributionCompany2 -> Add -> New Item...
  12. In the left list of the Add New Item dialog box, under Visual C# and under the Web node, click Markup
  13. In the middle list, click HTML Page
  14. Change the Name to BillEvaluation
  15. Click Add
  16. Change the document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Water Distribution Company - Bill Evaluation</title>
    <link href="WaterCompany.css" rel="stylesheet" />
    </head>
    <body>
    <div align="center">
        <h2>Water Distribution Company</h2>
        <h3>Bill Evaluation</h3>
    </div>
    
    <script type="text/javascript">
        var results = function () {
            var counterBeginning = parseFloat(document.BillEvaluation.meterReadingStart.value);
            var counterEnding = parseFloat(document.BillEvaluation.meterReadingEnd.value);
            var consumption = counterEnding - counterBeginning;
    
            var waterConsumption = consumption * 4.18 / 1000;
            var sewerMaintenance = consumption * 5.85 / 1000;
    
            var distro = (waterConsumption + sewerMaintenance) * 0.14286;
            var environment = (waterConsumption + sewerMaintenance) * 0.057792;
            var pmt = waterConsumption + sewerMaintenance + distro + environment;
    
            document.BillEvaluation.waterSewerUsage.value = consumption;
            document.BillEvaluation.waterUseCharges.value = waterConsumption;
            document.BillEvaluation.sewerUseCharges.value = sewerMaintenance;
            document.BillEvaluation.distributionCharges.value = distro;
            document.BillEvaluation.environmentCharges.value = environment;
            document.BillEvaluation.totalCharges.value = pmt;
        }
    </script>
        
    <div class="bill-container">
        <form name="BillEvaluation" method="post">    
            <table>
                <tr>
                    <td class="large bold">Meter Reading Start:</td>
                    <td><input type="number" name="meterReadingStart" class="txt-format" /> Gallons</td>
                </tr>
                <tr>
                    <td class="bold">Meter Reading End:</td>
                    <td><input type="number" name="meterReadingEnd" class="txt-format" /> Gallons</td>
                </tr>
                <tr>
                    <td>&nbsp;</td>
                    <td><input type="button" name="btnCalculate" value="Calculate" onclick="results()" /></td>
                </tr>
                <tr>
                    <td colspan="2"><hr /></td>
                </tr>
                <tr>
                    <td class="bold">Water and Sewer Usage:</td>
                    <td><input type="text" name="waterSewerUsage" class="txt-format" /> Gallons</td>
                </tr>
                <tr>
                    <td class="bold">Water Use Charges => 4.18 per 1,000 Gallons:</td>
                    <td><input type="text" name="waterUseCharges" /></td>
                </tr>
                <tr>
                    <td class="bold">Sewer Use Charges => 5.85 per 1,000 Gallons:</td>
                    <td><input type="text" name="sewerUseCharges" /></td>
                </tr>
                <tr>
                    <td class="bold">Distribution Charges:</td>
                    <td><input type="text" name="distributionCharges" /></td>
                </tr>
                <tr>
                    <td class="bold">Environment Charges:</td>
                    <td><input type="text" name="environmentCharges" /></td>
                </tr>
                <tr>
                    <td colspan="2"><hr /></td>
                </tr>
                <tr>
                    <td class="bold">Total Charges:</td>
                    <td><input type="text" name="totalCharges" /></td>
                </tr>
            </table>
        </form>
    </div>
    </body>
    </html>
  17. To execute the project, on the main menu, click Debug -> Start Without Debugging:

    Introducing Operators and Operands

  18. Close the browser and return to your programming environment

Passing Arguments to an Anonymous Function

To pass an argument to an anonymous function, inside its parentheses, enter a name for the argument. In the body of the function, ignore or use the argument based on the value it has. When calling the function using the variable to which it was assigned, pass the appropriate value. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Algebra</title>
</head>
<body>
<script type="text/javascript">
    var double = function (nbr) {

        var res = nbr * 2;
        document.Algebra.result.value = res;
    }
</script>

<form name="Algebra" method="post">
    <table>
        <tr>
            <td><b>Number:</b></td>
            <td>248.96</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" name="btnDouble" value="Double" onclick="double(248.96)" /></td>
        </tr>
        <tr>
            <td><b>Number:</b></td>
            <td><input type="number" name="result" /></td>
        </tr>
    </table>
</form>
</body>
</html>

In the same way, you can create an anonymous function that takes as many arguments as you want. When calling the function, pass the argument in the right order based on their types. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Payroll</title>
</head>
<body>
<script type="text/javascript">
    var present = function (first, nbr, last, status) {

        var salary = nbr * 40
        var name = last + ", " + first;

        document.Algebra.result.value = "Employee: " + name + ", Full Time? " + status + " Estimated Weekly Salary: " + salary;
    }
</script>

<form name="Algebra" method="post">
    <table>
        <tr>
            <td><b>Employed Full Time:</b></td>
            <td>True</td>
        </tr>
        <tr>
            <td><b>First Name:</b></td>
            <td>Martino</td>
        </tr>
        <tr>
            <td><b>Last Name:</b></td>
            <td>Hernandez</td>
        </tr>
        <tr>
            <td><b>Hourly Salary:</b></td>
            <td>24.08</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" name="btnSummarize" value="Summarize" onclick="present('Martino', 24.08, 'Hernandez', true)" /></td>
        </tr>
        <tr>
            <td><b>Employment Summary:</b></td>
            <td><textarea name="result" cols="50"></textarea></td>
        </tr>
    </table>
</form>
</body>
</html>

Arrow Functions

JavaScript supports lambda expressions in what it calls arrow functions. An arrow function is a function that is defined where it is needed, as opposed to defining it in one place and calling it in another place.

An arrow function is created without a name, without the function keyword, and using the => operator between the parentheses and the curly brackets. Therefore, the primary formula of an arrow function is:

() => {. . .}

As seen with anonymous functions, if you plan to call the function, you can first assign it to a variable, and then use that variable to call the function. Here is an example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Algebra</title>
<style type="text/css">
.bold      { font-weight: bold;   }
.center    { text-align:  center; }
.large     { width:       120px;  }
.container { margin:      auto;
             width:       300px;  }
</style>
</head>
<body>
<script type="text/javascript">
    function calculateDiameter(nbr) {
        return nbr * 2.00;
    }

    function calculateArea(nbr) {
        return nbr * nbr * 3.159;
    }

    var calculation = () => {
        var rad = parseFloat(document.Geometry.radius.value);

        document.Geometry.diameter.value = calculateDiameter(rad);
        document.Geometry.area.value = calculateArea(rad);
    }
</script>

<div class="container">
    <h2 class="center">Geometry - Circle</h2>
    
    <form name="Geometry" method="post">
        <table>
            <tr>
                <td class="large bold">Radius:</td>
                <td><input type="text" name="radius" /></td>
                <td><input type="button" name="btnCalculate" value="Calculate" onclick="calculation()" /></td>
            </tr>
            <tr>
                <td class="bold">Diameter:</td>
                <td><input type="number" name="diameter" /></td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td class="bold">Area:</td>
                <td><input type="text" name="area" /></td>
                <td>&nbsp;</td>
            </tr>
        </table>
     </form>
 </div>
</body>
</html>

Callback Functions

Callback Functions

A callback function is a function that is passed as argument to another function. The receiveing function B doesn't know and doesn't care how the argument function A works or what it does, but needs whatever behavior function A does so that function B can complete its work. In fact, function B doesn't check what function A does. At the right time, function B will need whatever it is supposed to get from function A. It is at that time that, if function A cannot produce the intended behavior or result, then function B may complain (or produce an error or an unreliable result). The topic of callback functions are not new. Callback functions probably get their origin in Assembly and/or C with the issue of pointers or function pointers.

Creating a Receiving Callback Function

In JavaScript, to create a function that takes a callback function as argument, simply provide a name for the argument (this is a little easier than in the other C-based functions where you must first define the callback function; we will see this issue with delegates in C#). Here is an example:

function receive(callback) {

}

At the time you judge it necessary, in the body of the function, apply the parentheses to the name of the argument to call the callback function. At that time, the receiving function will hand the processing to the callback function. This means that you must have defined the callback function. This would be done as follows:

function msgbox() {
    . . .
}

function receive(callback) {
    . . .

    callback();
            
    . . .
}

When calling the receving function, pass the name of a function that uses the same syntax as the argument. This would be done as follows:

function msgbox() {
    . . .
}

function receive(callback) {
    . . .

    callback();
            
    . . .
}

receive(msgbox);

A Callback Function with Arguments

A callback function can use one or more arguments. To start, create the function as normally as possible. When calling the callback function, pass the desired arguments to it.

Introduction to Built-In Functions

Introduction

To assist you in performing the most routine operations, JavaScript provides many ready-made functions you can use directly in your code. There are som many of the functions that we can review only a few.

Converting a Value to an Integer

If you create a form in which a user must type a value, by default, the value the user types is a string, primarily a piece of text. If you want to consider that a number and must involve it in a numerucal expression, you must convert it. To assist you with this, if the value is an integer, JavaScript provides a function named parseInt. The syntax of this function is:

int parseInt(string, radix);

This function takes one required argument and one optional argument. The requirement argument is the value that must be converted:

The second argument is valid only if the first one is, based on the above description. The second argument specifies the base by which the number will be converted. It is a number between 2 and 36. If you don't pass this argument, the number 10 would be used.

Converting a Value to a Floating-Point Number

To let you convert a value to a decimal number with a precision part, JavaScript provides a function namedparseFloat. Its syntax is:

decimal parseFloat(value);

This functakes one argument as the value to be conoverted:

Normally, a floating-point number is made of two sections separated by the character designated by as the desimal separater. If the argument is a number ;ike that, then the function will return it.

Practical LearningPractical Learning: Introducing Built-In Functions

  1. Change the Index.cshtml document as follows:
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>ESCAPE: Bill Evaluation</title>
    <link rel="stylesheet" type="text/css" href="CableCompany.css" />
    </head>
    <body>
    <div class="container">
        <h1 class="centered">ESCAPE</h1>
        <h2 class="centered">Eastern Shore Cable and Production Entertainment</h2>
        <h3 class="centered">Bill Evaluation</h3>
    </div>
    
    <div class="container">
        <form name="BillEvaluation" method="post">
            <fieldset>
                <legend>Cable TV Services</legend>
                <div>
                    <label for="CableTVBasicFee">Cable TV Basic Fee:</label>
                    <input type="number" id="CableTVBasicFee" name="CableTVBasicFee" value="0.00" />
                </div>
                <div>
                    <label for="DVRService">DVR Service:</label>
                    <input type="number" id="DVRService" name="DVRService" value="0.00" />
                </div>
                <div>
                    <label for="SportPackage">Sport Package:</label>
                    <input type="number" id="SportPackage" name="SportPackage" value="0.00" />
                </div>
                <div>
                    <div>
                        <input type="button" name="btnEvaluate" value="Evaluate" onclick="evaluatePayment()" />
                    </div>
                </div>
                <div>
                    <label for="PaymentAmount">Payment Amount:</label>
                    <input type="number" id="PaymentAmount" name="PaymentAmount" value="0.00" />
                </div>
            </fieldset>
        </form>
    </div>
    
    <script>
        function evaluatePayment() {
            'use strict';
            var basicFee = parseFloat(document.BillEvaluation.CableTVBasicFee.value);
            var dvr = parseFloat(document.BillEvaluation.DVRService.value);
            var sport = parseFloat(document.BillEvaluation.SportsPackage.value);
    
            var amount = basicFee + dvr + sport;
            document.BillEvaluation.PaymentAmount.value = amount;
        }
    </script>
    </body>
    </html>
  2. To execute the project, on the main menu, click Debug -> Start Without Debugging
  3. Change the values in the text boxes as follows:
    Cabel TV Basic Fee: 24.90
    DVR Service: 10.20
    Sports Package: 9.95
  4. Click the Evaluate button::

    Introduction to Functions

  5. Close the browser and return to your programming environment
  6. Close Microsoft Visual Studio

Previous Copyright © 2018-2019, FunctionX Next