Fundamentals of Functions in JavaScript

Introduction

A function is a section of code used to solve a particular problem. There are various categories of functions you will use in your projects. The primary category is a function you create.

Creating a Function

You can create a function in a webpage. You must first create a <SCRIPT> section in the document. You can add it in either the head or the body section. The primary formula to create a function is:

function function-name(){}

Start with the function keyword and end with (){}. A function must have a name. Although there are some rules you must follow and some you can ignore, in our lessons, when the name is in one word, we will use lowercase. Wehn the name is a combination of words, the first word will be in lowercase, the first letter of each subsequent word will be in uppercase.

A function must have parentheses. Depending on some situations, the parentheses may have something. At this time, we will leave them empty. The section from { to } is referred to as the body of the function. That's where you will write your code. For example, you can declare a variable. If a function is short, you write everything in one line. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Exercise</title>
</head>
<body>

<script>
    function move() { var number; }
</script>
</body>
</html>

If the function is using many pieces of code, you can spread it on many lines, such as putting the last curly bracket on its own line.

Just as you can create one function, you can create as many as you need.

In the body of a function, you can write the code you need. For example, as mentioned in the previous lesson, you can access the controls of a form. In the same way, you can create all types of expressions.

Practical LearningPractical Learning: Introducing Functions

  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 CableCompany1
  4. Click OK
  5. In the New ASP.NET Web Application dialog box, click the Empty icon and click OK
  6. To create a new CSS file, in the Solution Explorer, right-click CableCompany1 -> Add -> New Item...
  7. 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
  8. Change the file Name to CableCompany
  9. Click Add
  10. Change the document as follows:
    body {
        background-color: white;
    }
    
    form                        { padding:          1em;
                                  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  }
    .container h1               { margin:           auto;
                                  width:            600px;     }
    .container form             { margin:           auto;
                                  width:            280px;     }
    .centered                   { text-align:       center;    }
  11. In the Solution Explorer, right-click CableCompany1 -> Add -> New Item...
  12. In the left list of the Add New Item dialog box, under Visual C#, click Web
  13. In the middle list, click HTML Page
  14. Change the file Name to Index
  15. Click Add
  16. Change the 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="SportsPackage">Sports Package:</label>
                    <input type="number" id="SportsPackage" name="SportsPackage" value="0.00" />
                </div>
                <div>
                    <div>
                        <input type="button" name="btnEvaluate" value="Evaluate" />
                    </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 = 24.95;
            var dvr = 9.95;
            var sport = 8.95;
    
            var amount = basicFee + dvr + sport;
    
            document.BillEvaluation.CableTVBasicFee.value = basicFee;
            document.BillEvaluation.DVRService.value = dvr;
            document.BillEvaluation.SportsPackage.value = sport;
            document.BillEvaluation.PaymentAmount.value = amount;
        }
    </script>
    </body>
    </html>

Calling a Function

Introduction

After creating a function, accessing it is referred to as calling it. In order to call a function, you must know and use its name. Then, in the place where you want to use it, type the name of the function followed by parentheses. If the function is simply called, you should (sometimes must) end the call with a semicolon. Here is an example:

<script>
    function getFullName() {
        var fName = document.EmploymentApplication.firstName.value;
        var lName = document.EmploymentApplication.lastName.value;

        var employeeName = fName + " " + lName;
        document.EmploymentApplication.fullName.value = employeeName;
    }

    function communicate() {
        getFullName();
    }
</script>

We were introduced to events in the first lesson. If a function performs an action that should be dealt with when an event occurs on a tag, you can call the function in the quotes of the event. Don't use a semicolon.

Practical LearningPractical Learning: Calling a Function

  1. Change the 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">Sports Package:</label>
                    <input type="number" id="SportsPackage" name="SportsPackage" 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 = 24.95;
            var dvr = 9.90;
            var sport = 8.90;
    
            var amount = basicFee + dvr + sport;
    
            document.BillEvaluation.CableTVBasicFee.value = basicFee;
            document.BillEvaluation.DVRService.value = dvr;
            document.BillEvaluation.SportsPackage.value = sport;
            document.BillEvaluation.PaymentAmount.value = amount;
        }
    </script>
    </body>
    </html>
  2. To preview the result, press Ctrl + F5:

    Introduction to Functions

  3. Click the Evaluate button:

    Introduction to Functions

  4. Close the browser and return to your programming environment

Immediately Calling a Function

Earlier, we specified that you need the name of a function in order to call it. The JavaScript language provides a special way to create a function that is immediately called as soon as its associated webpage opens. The formula to create the function is:

(function() {
	statement1
    statement2
    . . .
    statement_n
})();

To proceed, define the function like any other, but include the whole function between parentheses. Outside those parentheses, to call the function, some some empty parentheses.

Introduction to Parameters and Arguments

Introduction to the Parameters of a Function

To perform its action(s), a function may need some values. If you are creating a function that will need external values, you must indicate it. To do this, in the parantheses of the function, enter a name that represents a value. Here is an example of a function that will need one value:

<script>
    function evaluateWeklySalary(salary) {
    }
</script>

The name you provide to the function is called a parameter. In the body of the function, you can use the parameter or ignore it completely. Otherwise, when using the parameter, you can involve it in any operation you want. Here is an example:

<script>
    'use strict';

    function evaluateWeklySalary(salary) {
        var netPay = salary * 40;

        document.SalaryEvaluation.hourlyRate.value = salary;
    }
</script>

Calling a Function that Uses a Parameter

To call a function that uses a parameter, you must provide a value for the parameter. The value provided in the parentheses of the function is called an argument. The action of providing a value in the parentheses of the function is referred to as passing an argument.

There are various ways you can pass an argument to a function. If you have the value you want to use, provide it in the parentheses of the function. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';

    function evaluateWeklySalary(salary) {
        var netPay = salary * 40;

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.netPay.value = netPay;
    }

    evaluateWeklySalary(24.75);
</script>
</body>
</html>

If the value is stored in a variable, you can pass the name of the variable to the function. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';

    var hourlyWage = 37.64;

    function evaluateWeklySalary(salary) {
        var netPay = salary * 40;

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.netPay.value = netPay;
    }

    evaluateWeklySalary(hourlyWage);
</script>
</body>
</html>

A Function With Many Parameters

A function can use as many parameters as you judge them necessary. When creating such a function, in its parentheses, provide a name for each parameter. The parameters are separated by commas. Here is an example:

<script>
    function showTimeWorked(timeWorked, payRate) {

    }
<script>

As mentioned earlier, you don't have to use the parameters in the body of the function. Otherwise, in the body of the function, you can use the parameters any appropriate way you want. Here is an example:

<script>
    function evaluateWeklySalary(payRate, time) {
        var netPay = payRate * time;
    }
</script>

Calling a Function of many Parameters

When calling a function that uses many parameters, you must provide a value for each parameter in the order the parameters appear in the parentheses. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    function evaluateWeklySalary(payRate, time) {
        var netPay = payRate * time;

        document.SalaryEvaluation.hourlyRate.value = payRate;
        document.SalaryEvaluation.timeWorked.value = time;
        document.SalaryEvaluation.netPay.value = netPay;
    }

    evaluateWeklySalary(17.52, 38);
</script>
</body>
</html>

Intermediate Characteristics of Functions

Function Overloading

Function overloading is the ability to have two or more functions with the same name in the same document. To have method overloading, each version of the overloaded function must have a different number of parameters. Here is an example:

function calculateBiweeklySalary() {
        
}

function calculateBiweeklySalary(yearlySalary) {

}

function calculateBiweeklySalary(payRate, monthlySalary) {
   
}

Default Arguments

When you call a function that has a parameter, you must remember to provide a value for the parameter. A function is said to have a default argument if the argument is primarily specified. For such a function, a value is assigned to the parameter when the function is created. When such as function is called, you can omit passing an argument. A function can also have many parameters where all of them would have dfeault values. A fuction can have many parameters with only some of them having default values.

The Scope and Lifetime of a Variable

Introduction

The scope of a variable is the extent to which it is available to other sections of a website. To manage this, a variable is said to have local or global scope.

Local Variables

A variable is said to be local if it is declared in the body of a function. Here is an example:

<script>
    function evaluateWeklySalary() {
        var time = 44.50;
    }
<script>

When a variable is declared locally, it can be accessed only by code inside the same curly brackets. If you try accessing such a variable outside its curly brackets, you would receive an error. The following code will produce an error because the time variable that is declared locally is being accessed outside that function:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    function evaluateWeklySalary(salary) {
        var time = 44.50;
        var netPay = salary * time;

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.timeWorked.value = time;
        document.SalaryEvaluation.netPay.value = netPay;
    }

    evaluateWeklySalary(22.28, time);
</script>
</body>
</html>

A Web Page-Based Variable

A variable that is declared in a webpage but outside any a function can be accessed by any function in the same webpage. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<script>
    var salary = 14.75;
</script>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var time = 44.00;

    function evaluateWeklySalary() {
        var netPay = salary * time;

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.timeWorked.value = time;
        document.SalaryEvaluation.netPay.value = netPay;
    }

    evaluateWeklySalary(salary, time);
</script>
</body>
</html>

A Function that Returns a Value

Introduction

If a function has carried its assignment, it may produce a result that other functions may need. Such a function is said to return a value. Once again, when creating the function, define what you want in it. There are many ways you can indicate that a function returns a value. The primary technique is that, before the closing curly bracket, type the return keyword followed by the value and a semicolon. Here is an example:

<script>
    function evaluateWeklySalary() {
        var netPay = salary * time;

        return netPay;
    }
</script>

Introduction to Calling a Function that Returns a Value

To use the value that a function returns, you must call that function. If you want, you can assign its call to a local variable. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWorked" /></td>
        </tr>
        <tr>
            <td>Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" value="Show Values" onclick="present()" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var time = 44.00;
    var salary = 14.75;

    function evaluateWeklySalary() {
        var netPay = salary * time;

        return netPay;
    }

    function present() {
        var weeklySalary;

        weeklySalary = evaluateWeklySalary();

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.timeWorked.value = time;
        document.SalaryEvaluation.netPay.value = weeklySalary;

    }
</script>
</body>
</html>

Techniques of Calling a Function that Returns a Value

You can call a function that returns a value as you do for one that doen't return a value. In the above code, we first declared a variable in one line and called the function in another line. This is done in case the values of the variable may change. Otherwise, you can declare the variable on the same line where you are calling the function. Here is an example:

<script>
    'use strict';
    var time = 44.00;
    var salary = 14.75;

    function evaluateWeklySalary() {
        var netPay = salary * time;

        return netPay;
    }

    function present() {
        var weeklySalary = evaluateWeklySalary();

        document.SalaryEvaluation.hourlyRate.value = salary;
        document.SalaryEvaluation.timeWorked.value = time;
        document.SalaryEvaluation.netPay.value = weeklySalary;

    }
</script>

In the previous two examples, we declared a variable to store the return value of the function. This is done if you plan to use the variable many times, or call the function many times, or if the value of the variable will change more than once. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
    </table>
    <table>
        <tr>
            <td>Time Worked</td>
            <td>Week 1</td>
            <td>Week 2</td>
        </tr>
        <tr>
            <td>Monday</td>
            <td><input type="text" name="mondayWeek1" /></td>
            <td><input type="text" name="mondayWeek2" /></td>
        </tr>
        <tr>
            <td>Tuesday</td>
            <td><input type="text" name="tuesdayWeek1" /></td>
            <td><input type="text" name="tuesdayWeek2" /></td>
        </tr>
        <tr>
            <td>Wednesday</td>
            <td><input type="text" name="wednesdayWeek1" /></td>
            <td><input type="text" name="wednesdayWeek2" /></td>
        </tr>
        <tr>
            <td>Thursday</td>
            <td><input type="text" name="thursdayWeek1" /></td>
            <td><input type="text" name="thursdayWeek2" /></td>
        </tr>
        <tr>
            <td>Friday</td>
            <td><input type="text" name="fridayWeek1" /></td>
            <td><input type="text" name="fridayWeek2" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWeek1" /></td>
            <td><input type="text" name="timeWeek2" /></td>
        </tr>
        <tr>
            <td>Weekly Salary:</td>
            <td><input type="text" name="weeklySalary1" /></td>
            <td><input type="text" name="weeklySalary2" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="text-align: right">Net Pay:</td>
            <td><input type="text" name="netPay" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><input type="button" value="Show Values" onclick="present()" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var rate = 24.59;
    var mon1 =  8.00, tue1 = 10.50, wed1 = 9.00, thu1 = 8.50, fri1 = 8.00;
    var mon2 = 10.00, tue2 =  7.00, wed2 = 6.50, thu2 = 9.00, fri2 = 9.50;

    function calculateTime(day1, day2, day3, day4, day5) {
        var total = day1 + day2 + day3 + day4 + day5;

        return total;
    }

    function add(value1, value2) {
        return value1 + value2;
    }

    function multiply(value1, value2) {
        return value1 * value2;
    }

    function present() {
        var week1Time = calculateTime(mon1, tue1, wed1, thu1, fri1);
        var week2Time = calculateTime(mon2, tue2, wed2, thu2, fri2);
        var week1Salary = multiply(rate, week1Time);
        var week2Salary = multiply(rate, week2Time);
        var netPay = week1Salary + week2Salary;

        document.SalaryEvaluation.mondayWeek1.value = mon1;
        document.SalaryEvaluation.tuesdayWeek1.value = tue1;
        document.SalaryEvaluation.wednesdayWeek1.value = wed1;
        document.SalaryEvaluation.thursdayWeek1.value = thu1;
        document.SalaryEvaluation.fridayWeek1.value = fri1;

        document.SalaryEvaluation.mondayWeek2.value = mon2;
        document.SalaryEvaluation.tuesdayWeek2.value = tue2;
        document.SalaryEvaluation.wednesdayWeek2.value = wed2;
        document.SalaryEvaluation.thursdayWeek2.value = thu2;
        document.SalaryEvaluation.fridayWeek2.value = fri2;

        document.SalaryEvaluation.hourlyRate.value = rate;
        document.SalaryEvaluation.timeWeek1.value = week1Time;
        document.SalaryEvaluation.timeWeek2.value = week2Time;
        document.SalaryEvaluation.weeklySalary1.value = week1Salary;
        document.SalaryEvaluation.weeklySalary2.value = week2Salary;
        document.SalaryEvaluation.netPay.value = netPay;
    }
</script>
</body>
</html>

If you are planning to call the function once, of if you don't need to store its value in a variable, you can call the function directly where its value is needed. Here is an example:

<script>
    'use strict';
    var rate = 24.59;
    var mon1 =  8.00, tue1 = 10.50, wed1 = 9.00, thu1 = 8.50, fri1 = 8.00;
    var mon2 = 10.00, tue2 =  7.00, wed2 = 6.50, thu2 = 9.00, fri2 = 9.50;

    function calculateTime(day1, day2, day3, day4, day5) {
        var total = day1 + day2 + day3 + day4 + day5;

        return total;
    }

    function add(value1, value2) {
        return value1 + value2;
    }

    function multiply(value1, value2) {
        return value1 * value2;
    }

    function present() {
        var week1Salary = multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1));
        var week2Salary = multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2));
        var netPay = week1Salary + week2Salary;

        document.SalaryEvaluation.mondayWeek1.value = mon1;
        document.SalaryEvaluation.tuesdayWeek1.value = tue1;
        document.SalaryEvaluation.wednesdayWeek1.value = wed1;
        document.SalaryEvaluation.thursdayWeek1.value = thu1;
        document.SalaryEvaluation.fridayWeek1.value = fri1;

        document.SalaryEvaluation.mondayWeek2.value = mon2;
        document.SalaryEvaluation.tuesdayWeek2.value = tue2;
        document.SalaryEvaluation.wednesdayWeek2.value = wed2;
        document.SalaryEvaluation.thursdayWeek2.value = thu2;
        document.SalaryEvaluation.fridayWeek2.value = fri2;

        document.SalaryEvaluation.hourlyRate.value = rate;
        document.SalaryEvaluation.timeWeek1.value = calculateTime(mon1, tue1, wed1, thu1, fri1);
        document.SalaryEvaluation.timeWeek2.value = calculateTime(mon2, tue2, wed2, thu2, fri2);
        document.SalaryEvaluation.weeklySalary1.value = week1Salary;
        document.SalaryEvaluation.weeklySalary2.value = week2Salary;
        document.SalaryEvaluation.netPay.value = netPay;
    }
</script>

Here is another version of the same code:

<script>
    'use strict';
    var rate = 24.59;
    var mon1 =  8.00, tue1 = 10.50, wed1 = 9.00, thu1 = 8.50, fri1 = 8.00;
    var mon2 = 10.00, tue2 =  7.00, wed2 = 6.50, thu2 = 9.00, fri2 = 9.50;

    function calculateTime(day1, day2, day3, day4, day5) {
        var total = day1 + day2 + day3 + day4 + day5;

        return total;
    }

    function add(value1, value2) {
        return value1 + value2;
    }

    function multiply(value1, value2) {
        return value1 * value2;
    }

    function present() {
        var netPay = multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1)) + multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2));

        document.SalaryEvaluation.mondayWeek1.value = mon1;
        document.SalaryEvaluation.tuesdayWeek1.value = tue1;
        document.SalaryEvaluation.wednesdayWeek1.value = wed1;
        document.SalaryEvaluation.thursdayWeek1.value = thu1;
        document.SalaryEvaluation.fridayWeek1.value = fri1;

        document.SalaryEvaluation.mondayWeek2.value = mon2;
        document.SalaryEvaluation.tuesdayWeek2.value = tue2;
        document.SalaryEvaluation.wednesdayWeek2.value = wed2;
        document.SalaryEvaluation.thursdayWeek2.value = thu2;
        document.SalaryEvaluation.fridayWeek2.value = fri2;

        document.SalaryEvaluation.hourlyRate.value = rate;
        document.SalaryEvaluation.timeWeek1.value = calculateTime(mon1, tue1, wed1, thu1, fri1);
        document.SalaryEvaluation.timeWeek2.value = calculateTime(mon2, tue2, wed2, thu2, fri2);
        document.SalaryEvaluation.weeklySalary1.value = multiply(rate, calculateTime(mon1, tue1, wed1, thu1, fri1));
        document.SalaryEvaluation.weeklySalary2.value = multiply(rate, calculateTime(mon2, tue2, wed2, thu2, fri2));
        document.SalaryEvaluation.netPay.value = netPay;
    }
</script>

Nesting a Function

Introduction

Nesting a function is the ability to create a function in the body of another function. JavaScript is one of the languages that support this feature.

Creating a Nested Function

To nest a function, in the body of an existing function, create a function using the function keyword, the parentheses, and a body delimited by curly brackets. The nested function doesn't need a name. Assign that nested function to a variable. In the body of the nested function, perform the operations you want. Here is an example:

<script>
    'use strict';
    var rate = 28.75;
    var work = 41.50;

    function present() {
        var calculate = function () {
            var total = rate * work;
        }
    }
</script>
</body>
</html>

When a function has been nested, it is hidden from outside its nesting (or parent) function. This means that the objects outside the nesting function cannot directly access the nested function and the outside functions cannot call it. Of course the parent function can be called by anything in the script. If the nested function contains operations that other objects or functions may need, you can first call the nested function somewhere in the body of its parent function. After that, a call to its parent function would give access to the nested function. Here is an example:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td>Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" /></td>
        </tr>
        <tr>
            <td>Time Worked:</td>
            <td><input type="text" name="timeWorked" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td><input type="button" name="btnCalculate" value="Calculate" onclick="present()" /></td>
        </tr>
        <tr>
            <td>Total Salary:</td>
            <td><input type="text" name="totalSalary" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var rate = 28.75;
    var work = 41.50;

    function present() {
        var calculate = function () {
            var total = rate * work;

            document.SalaryEvaluation.hourlyRate.value = rate;
            document.SalaryEvaluation.timeWorked.value = work;
            document.SalaryEvaluation.totalSalary.value = total;
        }

        calculate();
    }
</script>
</body>
</html>

In the same way, you can create as many functions as you want in the body of an existing function. Once again, in the outside objects and functions need the jobs of the nested functions, you must call the nested functions before the end of the parent function. When the parent function is called, all the nested functions also execute (provide you had called them). Otherwise, you can call the nested functions inside the nesting function. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td style="font-weight: 800;">Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" style="width: 80px" /></td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="font-weight: 600;">Week 1</td>
            <td style="font-weight: 600;">Week 2</td>
        </tr>
        <tr>
            <td style="font-weight: 800;">Time Worked:</td>
            <td><input type="text" name="timeWorkedWeek1" style="width: 80px" /></td>
            <td><input type="text" name="timeWorkedWeek2" style="width: 80px" /></td>
        </tr>
        <tr>
            <td style="font-weight: 800;">Weekly Salaries:</td>
            <td><input type="text" name="salaryWeek1" style="width: 80px" /></td>
            <td><input type="text" name="salaryWeek2" style="width: 80px" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="font-weight: 800;">Net Pay:</td>
            <td><input type="text" name="netPay" style="width: 80px" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><input type="button" name="btnCalculate" value="Calculate" onclick="present()" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var rate = 23.78;
    var week1 = 42.00;
    var week2 = 44.50;

    function present() {
        var calculate1 = function () {
            return rate * week1;
        }
        var calculate2 = function () {
            return rate * week2;
        }

        var calculateTotal = function () {
            var salary1 = calculate1();
            var salary2 = calculate2();

            return salary1 + salary2;
        }

        document.SalaryEvaluation.hourlyRate.value = rate;
        document.SalaryEvaluation.timeWorkedWeek1.value = week1;
        document.SalaryEvaluation.timeWorkedWeek2.value = week2;
        document.SalaryEvaluation.salaryWeek1.value = calculate1();
        document.SalaryEvaluation.salaryWeek2.value = calculate2();
        document.SalaryEvaluation.netPay.value = calculateTotal();
    }
</script>
</body>
</html>

Passing Arguments to a Nested Function

You can create a nested function that uses one or more parameters. Create the function like any other. When you decide to call the nested function, remember to provide a value for each parameter. Here are examples:

<!DOCTYPE html>
<html>
<head>
<title>Salary Evaluation</title>
</head>
<body>
<h1>Salary Evaluation</h1>

<form name="SalaryEvaluation">
    <table>
        <tr>
            <td style="font-weight: 800;">Hourly Rate:</td>
            <td><input type="text" name="hourlyRate" style="width: 80px" /></td>
            <td>&nbsp;</td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="font-weight: 600;">Week 1</td>
            <td style="font-weight: 600;">Week 2</td>
        </tr>
        <tr>
            <td style="font-weight: 800;">Time Worked:</td>
            <td><input type="text" name="timeWorkedWeek1" style="width: 80px" /></td>
            <td><input type="text" name="timeWorkedWeek2" style="width: 80px" /></td>
        </tr>
        <tr>
            <td style="font-weight: 800;">Weekly Salaries:</td>
            <td><input type="text" name="salaryWeek1" style="width: 80px" /></td>
            <td><input type="text" name="salaryWeek2" style="width: 80px" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td style="font-weight: 800;">Net Pay:</td>
            <td><input type="text" name="netPay" style="width: 80px" /></td>
        </tr>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td><input type="button" name="btnCalculate" value="Calculate" onclick="present()" /></td>
        </tr>
    </table>
</form>

<script>
    'use strict';
    var rate = 17.83;
    var week1 = 39.00;
    var week2 = 42.00;

    function present() {
        // This is an example of a nested function that takes an argument
        function doItToMe(something) {

        }
        
        // Here are examples nested functions that take two arguments each
        var addition = function (value1, value2) { return value1 + value2; }
        var multiplication = function (value1, value2) { return value1 * value2; }

        var calculateTotal = function () {
            // Calling a nested function
            var salary1 = multiplication(rate, week1);
            var salary2 = multiplication(rate, week2);

            // Calling another nested function
            return addition(salary1, salary2);
        }

        document.SalaryEvaluation.hourlyRate.value = rate;
        document.SalaryEvaluation.timeWorkedWeek1.value = week1;

        document.SalaryEvaluation.timeWorkedWeek2.value = week2;
        // Calling a nested function
        document.SalaryEvaluation.salaryWeek1.value = multiplication(rate, week1);
        // Calling a nested function
        document.SalaryEvaluation.salaryWeek2.value = multiplication(rate, week2);
        document.SalaryEvaluation.netPay.value = calculateTotal();
    }

    // Calling a nested function that takes an argument
    doItToMe('anything');
</script>
</body>
</html>

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

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.

JavaScript Libraries and Functions

Both the AngularJS and the jQuery libraries support functions exactly as they are used in JavaScript as we saw in this lesson.

Practical LearningPractical Learning: Ending the Lesson


Previous Copyright © 2018-2019, FunctionX Next